nlink 0.13.0

Async netlink library for Linux network configuration
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
//! IP address management.
//!
//! This module provides typed builders for adding and managing IP addresses.
//!
//! # Example
//!
//! ```ignore
//! use nlink::netlink::{Connection, Route};
//! use nlink::netlink::addr::{Ipv4Address, Ipv6Address, AddressFlags};
//! use std::net::{Ipv4Addr, Ipv6Addr};
//!
//! let conn = Connection::<Route>::new()?;
//!
//! // Add an IPv4 address
//! conn.add_address(
//!     Ipv4Address::new("eth0", Ipv4Addr::new(192, 168, 1, 100), 24)
//!         .broadcast(Ipv4Addr::new(192, 168, 1, 255))
//!         .label("eth0:web")
//! ).await?;
//!
//! // Add an IPv6 address with lifetimes
//! conn.add_address(
//!     Ipv6Address::new("eth0", "2001:db8::1".parse()?, 64)
//!         .preferred_lifetime(3600)
//!         .valid_lifetime(7200)
//! ).await?;
//!
//! // Delete an address
//! conn.del_address("eth0", Ipv4Addr::new(192, 168, 1, 100), 24).await?;
//! ```
//!
//! # Namespace-Safe Operations
//!
//! When working with network namespaces, use the index-based constructors
//! to avoid sysfs lookups:
//!
//! ```ignore
//! use nlink::netlink::{Connection, Route, namespace};
//! use nlink::netlink::addr::Ipv4Address;
//!
//! // Create connection to namespace
//! let conn = namespace::connection_for("myns")?;
//!
//! // Get interface index via netlink (namespace-safe)
//! let link = conn.get_link_by_name("eth0").await?.unwrap();
//!
//! // Use index-based constructor
//! conn.add_address(
//!     Ipv4Address::with_index(link.ifindex(), "10.0.0.1".parse()?, 24)
//! ).await?;
//! ```

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use super::{
    builder::MessageBuilder,
    connection::Connection,
    error::Result,
    interface_ref::InterfaceRef,
    message::{NLM_F_ACK, NLM_F_REQUEST, NlMsgType},
    protocol::Route,
    types::addr::{IfAddrMsg, IfaAttr, Scope, ifa_flags},
};

/// NLM_F_CREATE flag
const NLM_F_CREATE: u16 = 0x400;
/// NLM_F_EXCL flag
const NLM_F_EXCL: u16 = 0x200;
/// NLM_F_REPLACE flag
const NLM_F_REPLACE: u16 = 0x100;

/// Address families
pub const AF_INET: u8 = 2;
pub const AF_INET6: u8 = 10;

/// Trait for address configurations that can be added.
///
/// This trait separates interface reference from message building.
/// The Connection is responsible for resolving the interface reference
/// to an index before calling the write methods.
pub trait AddressConfig: Send + Sync {
    /// Get the interface reference (name or index).
    fn interface_ref(&self) -> &InterfaceRef;

    /// Get the address family (AF_INET or AF_INET6).
    fn family(&self) -> u8;

    /// Get the prefix length.
    fn prefix_len(&self) -> u8;

    /// Write the "add address" message to the builder.
    ///
    /// The `ifindex` parameter is the resolved interface index.
    fn write_add(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()>;

    /// Write the "replace address" message to the builder.
    ///
    /// The `ifindex` parameter is the resolved interface index.
    fn write_replace(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()>;

    /// Write the "delete address" message to the builder.
    ///
    /// The `ifindex` parameter is the resolved interface index.
    fn write_delete(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()>;
}

/// Cache info structure for address lifetimes.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
struct IfaCacheinfo {
    /// Preferred lifetime in seconds (INFINITY_LIFE_TIME for forever)
    ifa_prefered: u32,
    /// Valid lifetime in seconds (INFINITY_LIFE_TIME for forever)
    ifa_valid: u32,
    /// Creation timestamp (unused for add)
    cstamp: u32,
    /// Update timestamp (unused for add)
    tstamp: u32,
}

/// Infinity lifetime value (0xFFFFFFFF)
pub const INFINITY_LIFE_TIME: u32 = 0xFFFFFFFF;

// ============================================================================
// IPv4 Address
// ============================================================================

/// Configuration for an IPv4 address.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::addr::Ipv4Address;
/// use std::net::Ipv4Addr;
///
/// let addr = Ipv4Address::new("eth0", Ipv4Addr::new(192, 168, 1, 100), 24)
///     .broadcast(Ipv4Addr::new(192, 168, 1, 255))
///     .label("eth0:web")
///     .scope(nlink::netlink::types::addr::Scope::Universe);
///
/// conn.add_address(addr).await?;
/// ```
#[derive(Debug, Clone)]
pub struct Ipv4Address {
    interface: InterfaceRef,
    address: Ipv4Addr,
    prefix_len: u8,
    /// Peer address for point-to-point links
    peer: Option<Ipv4Addr>,
    /// Broadcast address
    broadcast: Option<Ipv4Addr>,
    /// Address label (max 15 chars + null)
    label: Option<String>,
    /// Address scope
    scope: Scope,
    /// Address flags
    flags: u32,
    /// Preferred lifetime in seconds
    preferred_lft: Option<u32>,
    /// Valid lifetime in seconds
    valid_lft: Option<u32>,
    /// Route metric/priority
    metric: Option<u32>,
}

impl Ipv4Address {
    /// Create a new IPv4 address configuration.
    ///
    /// # Arguments
    ///
    /// * `interface` - Interface name (e.g., "eth0")
    /// * `address` - IPv4 address
    /// * `prefix_len` - Prefix length (0-32)
    pub fn new(interface: impl Into<String>, address: Ipv4Addr, prefix_len: u8) -> Self {
        Self {
            interface: InterfaceRef::Name(interface.into()),
            address,
            prefix_len,
            peer: None,
            broadcast: None,
            label: None,
            scope: Scope::Universe,
            flags: 0,
            preferred_lft: None,
            valid_lft: None,
            metric: None,
        }
    }

    /// Create a new IPv4 address configuration with interface index.
    ///
    /// Use this constructor for namespace-safe operations when you have
    /// already resolved the interface index via `conn.get_link_by_name()`.
    ///
    /// # Arguments
    ///
    /// * `ifindex` - Interface index
    /// * `address` - IPv4 address
    /// * `prefix_len` - Prefix length (0-32)
    pub fn with_index(ifindex: u32, address: Ipv4Addr, prefix_len: u8) -> Self {
        Self {
            interface: InterfaceRef::Index(ifindex),
            address,
            prefix_len,
            peer: None,
            broadcast: None,
            label: None,
            scope: Scope::Universe,
            flags: 0,
            preferred_lft: None,
            valid_lft: None,
            metric: None,
        }
    }

    /// Set the peer address for point-to-point links.
    pub fn peer(mut self, peer: Ipv4Addr) -> Self {
        self.peer = Some(peer);
        self
    }

    /// Set the broadcast address.
    ///
    /// If not set, the kernel will compute it automatically.
    pub fn broadcast(mut self, broadcast: Ipv4Addr) -> Self {
        self.broadcast = Some(broadcast);
        self
    }

    /// Set an address label.
    ///
    /// Labels are used for compatibility with older tools and can be
    /// used to identify addresses (e.g., "eth0:web").
    /// Maximum 15 characters.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        let mut l = label.into();
        if l.len() > 15 {
            l.truncate(15);
        }
        self.label = Some(l);
        self
    }

    /// Set the address scope.
    pub fn scope(mut self, scope: Scope) -> Self {
        self.scope = scope;
        self
    }

    /// Mark as secondary address.
    pub fn secondary(mut self) -> Self {
        self.flags |= ifa_flags::SECONDARY;
        self
    }

    /// Disable prefix route creation.
    pub fn noprefixroute(mut self) -> Self {
        self.flags |= ifa_flags::NOPREFIXROUTE;
        self
    }

    /// Set home address flag (Mobile IPv6).
    pub fn home(mut self) -> Self {
        self.flags |= ifa_flags::HOMEADDRESS;
        self
    }

    /// Set the preferred lifetime in seconds.
    ///
    /// Use `INFINITY_LIFE_TIME` for forever.
    pub fn preferred_lifetime(mut self, seconds: u32) -> Self {
        self.preferred_lft = Some(seconds);
        self
    }

    /// Set the valid lifetime in seconds.
    ///
    /// Use `INFINITY_LIFE_TIME` for forever.
    pub fn valid_lifetime(mut self, seconds: u32) -> Self {
        self.valid_lft = Some(seconds);
        self
    }

    /// Set the route metric/priority.
    pub fn metric(mut self, metric: u32) -> Self {
        self.metric = Some(metric);
        self
    }

    /// Write common address attributes to the builder.
    fn write_common_attrs(&self, builder: &mut MessageBuilder) {
        // IFA_LOCAL (the actual address on this interface)
        builder.append_attr(IfaAttr::Local as u16, &self.address.octets());

        // IFA_ADDRESS (peer address for ptp, or same as local)
        if let Some(peer) = self.peer {
            builder.append_attr(IfaAttr::Address as u16, &peer.octets());
        } else {
            builder.append_attr(IfaAttr::Address as u16, &self.address.octets());
        }

        // IFA_BROADCAST
        if let Some(brd) = self.broadcast {
            builder.append_attr(IfaAttr::Broadcast as u16, &brd.octets());
        }

        // IFA_LABEL
        if let Some(ref label) = self.label {
            builder.append_attr_str(IfaAttr::Label as u16, label);
        }

        // IFA_FLAGS (extended flags, 32-bit)
        if self.flags != 0 {
            builder.append_attr_u32(IfaAttr::Flags as u16, self.flags);
        }

        // IFA_CACHEINFO (lifetimes)
        if self.preferred_lft.is_some() || self.valid_lft.is_some() {
            let cacheinfo = IfaCacheinfo {
                ifa_prefered: self.preferred_lft.unwrap_or(INFINITY_LIFE_TIME),
                ifa_valid: self.valid_lft.unwrap_or(INFINITY_LIFE_TIME),
                cstamp: 0,
                tstamp: 0,
            };
            // SAFETY: IfaCacheinfo is a #[repr(C)] struct of u32 fields with no padding.
            // The pointer and size are valid for the lifetime of `cacheinfo`.
            let bytes = unsafe {
                std::slice::from_raw_parts(
                    &cacheinfo as *const IfaCacheinfo as *const u8,
                    std::mem::size_of::<IfaCacheinfo>(),
                )
            };
            builder.append_attr(IfaAttr::Cacheinfo as u16, bytes);
        }

        // IFA_RT_PRIORITY (metric)
        if let Some(metric) = self.metric {
            builder.append_attr_u32(IfaAttr::RtPriority as u16, metric);
        }
    }
}

impl AddressConfig for Ipv4Address {
    fn interface_ref(&self) -> &InterfaceRef {
        &self.interface
    }

    fn family(&self) -> u8 {
        AF_INET
    }

    fn prefix_len(&self) -> u8 {
        self.prefix_len
    }

    fn write_add(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()> {
        // Build ifaddrmsg
        let ifaddr = IfAddrMsg::new()
            .with_family(AF_INET)
            .with_prefixlen(self.prefix_len)
            .with_index(ifindex)
            .with_scope(self.scope as u8);

        builder.append(&ifaddr);
        self.write_common_attrs(builder);
        Ok(())
    }

    fn write_replace(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()> {
        // Same as write_add - the flags are set by the Connection
        let ifaddr = IfAddrMsg::new()
            .with_family(AF_INET)
            .with_prefixlen(self.prefix_len)
            .with_index(ifindex)
            .with_scope(self.scope as u8);

        builder.append(&ifaddr);
        self.write_common_attrs(builder);
        Ok(())
    }

    fn write_delete(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()> {
        let ifaddr = IfAddrMsg::new()
            .with_family(AF_INET)
            .with_prefixlen(self.prefix_len)
            .with_index(ifindex);

        builder.append(&ifaddr);

        // IFA_LOCAL
        builder.append_attr(IfaAttr::Local as u16, &self.address.octets());

        Ok(())
    }
}

// ============================================================================
// IPv6 Address
// ============================================================================

/// Configuration for an IPv6 address.
///
/// # Example
///
/// ```ignore
/// use nlink::netlink::addr::Ipv6Address;
/// use std::net::Ipv6Addr;
///
/// let addr = Ipv6Address::new("eth0", "2001:db8::1".parse()?, 64)
///     .preferred_lifetime(3600)
///     .valid_lifetime(7200)
///     .nodad();
///
/// conn.add_address(addr).await?;
/// ```
#[derive(Debug, Clone)]
pub struct Ipv6Address {
    interface: InterfaceRef,
    address: Ipv6Addr,
    prefix_len: u8,
    /// Peer address for point-to-point links
    peer: Option<Ipv6Addr>,
    /// Address scope
    scope: Scope,
    /// Address flags
    flags: u32,
    /// Preferred lifetime in seconds
    preferred_lft: Option<u32>,
    /// Valid lifetime in seconds
    valid_lft: Option<u32>,
    /// Route metric/priority
    metric: Option<u32>,
}

impl Ipv6Address {
    /// Create a new IPv6 address configuration.
    ///
    /// # Arguments
    ///
    /// * `interface` - Interface name (e.g., "eth0")
    /// * `address` - IPv6 address
    /// * `prefix_len` - Prefix length (0-128)
    pub fn new(interface: impl Into<String>, address: Ipv6Addr, prefix_len: u8) -> Self {
        Self {
            interface: InterfaceRef::Name(interface.into()),
            address,
            prefix_len,
            peer: None,
            scope: Scope::Universe,
            flags: 0,
            preferred_lft: None,
            valid_lft: None,
            metric: None,
        }
    }

    /// Create a new IPv6 address configuration with interface index.
    ///
    /// Use this constructor for namespace-safe operations when you have
    /// already resolved the interface index via `conn.get_link_by_name()`.
    ///
    /// # Arguments
    ///
    /// * `ifindex` - Interface index
    /// * `address` - IPv6 address
    /// * `prefix_len` - Prefix length (0-128)
    pub fn with_index(ifindex: u32, address: Ipv6Addr, prefix_len: u8) -> Self {
        Self {
            interface: InterfaceRef::Index(ifindex),
            address,
            prefix_len,
            peer: None,
            scope: Scope::Universe,
            flags: 0,
            preferred_lft: None,
            valid_lft: None,
            metric: None,
        }
    }

    /// Set the peer address for point-to-point links.
    pub fn peer(mut self, peer: Ipv6Addr) -> Self {
        self.peer = Some(peer);
        self
    }

    /// Set the address scope.
    pub fn scope(mut self, scope: Scope) -> Self {
        self.scope = scope;
        self
    }

    /// Disable Duplicate Address Detection.
    pub fn nodad(mut self) -> Self {
        self.flags |= ifa_flags::NODAD;
        self
    }

    /// Set optimistic DAD flag.
    pub fn optimistic(mut self) -> Self {
        self.flags |= ifa_flags::OPTIMISTIC;
        self
    }

    /// Disable prefix route creation.
    pub fn noprefixroute(mut self) -> Self {
        self.flags |= ifa_flags::NOPREFIXROUTE;
        self
    }

    /// Set home address flag (Mobile IPv6).
    pub fn home(mut self) -> Self {
        self.flags |= ifa_flags::HOMEADDRESS;
        self
    }

    /// Enable management of temporary addresses.
    pub fn mngtmpaddr(mut self) -> Self {
        self.flags |= ifa_flags::MANAGETEMPADDR;
        self
    }

    /// Set the preferred lifetime in seconds.
    ///
    /// Use `INFINITY_LIFE_TIME` for forever.
    pub fn preferred_lifetime(mut self, seconds: u32) -> Self {
        self.preferred_lft = Some(seconds);
        self
    }

    /// Set the valid lifetime in seconds.
    ///
    /// Use `INFINITY_LIFE_TIME` for forever.
    pub fn valid_lifetime(mut self, seconds: u32) -> Self {
        self.valid_lft = Some(seconds);
        self
    }

    /// Set the route metric/priority.
    pub fn metric(mut self, metric: u32) -> Self {
        self.metric = Some(metric);
        self
    }

    /// Write common address attributes to the builder.
    fn write_common_attrs(&self, builder: &mut MessageBuilder) {
        // IFA_LOCAL
        builder.append_attr(IfaAttr::Local as u16, &self.address.octets());

        // IFA_ADDRESS (peer or same as local)
        if let Some(peer) = self.peer {
            builder.append_attr(IfaAttr::Address as u16, &peer.octets());
        } else {
            builder.append_attr(IfaAttr::Address as u16, &self.address.octets());
        }

        // IFA_FLAGS (extended flags, 32-bit)
        if self.flags != 0 {
            builder.append_attr_u32(IfaAttr::Flags as u16, self.flags);
        }

        // IFA_CACHEINFO (lifetimes)
        if self.preferred_lft.is_some() || self.valid_lft.is_some() {
            let cacheinfo = IfaCacheinfo {
                ifa_prefered: self.preferred_lft.unwrap_or(INFINITY_LIFE_TIME),
                ifa_valid: self.valid_lft.unwrap_or(INFINITY_LIFE_TIME),
                cstamp: 0,
                tstamp: 0,
            };
            // SAFETY: IfaCacheinfo is a #[repr(C)] struct of u32 fields with no padding.
            // The pointer and size are valid for the lifetime of `cacheinfo`.
            let bytes = unsafe {
                std::slice::from_raw_parts(
                    &cacheinfo as *const IfaCacheinfo as *const u8,
                    std::mem::size_of::<IfaCacheinfo>(),
                )
            };
            builder.append_attr(IfaAttr::Cacheinfo as u16, bytes);
        }

        // IFA_RT_PRIORITY (metric)
        if let Some(metric) = self.metric {
            builder.append_attr_u32(IfaAttr::RtPriority as u16, metric);
        }
    }
}

impl AddressConfig for Ipv6Address {
    fn interface_ref(&self) -> &InterfaceRef {
        &self.interface
    }

    fn family(&self) -> u8 {
        AF_INET6
    }

    fn prefix_len(&self) -> u8 {
        self.prefix_len
    }

    fn write_add(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()> {
        let ifaddr = IfAddrMsg::new()
            .with_family(AF_INET6)
            .with_prefixlen(self.prefix_len)
            .with_index(ifindex)
            .with_scope(self.scope as u8);

        builder.append(&ifaddr);
        self.write_common_attrs(builder);
        Ok(())
    }

    fn write_replace(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()> {
        let ifaddr = IfAddrMsg::new()
            .with_family(AF_INET6)
            .with_prefixlen(self.prefix_len)
            .with_index(ifindex)
            .with_scope(self.scope as u8);

        builder.append(&ifaddr);
        self.write_common_attrs(builder);
        Ok(())
    }

    fn write_delete(&self, builder: &mut MessageBuilder, ifindex: u32) -> Result<()> {
        let ifaddr = IfAddrMsg::new()
            .with_family(AF_INET6)
            .with_prefixlen(self.prefix_len)
            .with_index(ifindex);

        builder.append(&ifaddr);

        // IFA_LOCAL
        builder.append_attr(IfaAttr::Local as u16, &self.address.octets());

        Ok(())
    }
}

// ============================================================================
// Connection Methods
// ============================================================================

impl Connection<Route> {
    /// Add an IP address to an interface.
    ///
    /// This method is namespace-safe: interface names are resolved via netlink,
    /// which queries the namespace that this connection is bound to.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use nlink::netlink::addr::{Ipv4Address, Ipv6Address};
    /// use std::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// // Add IPv4 address
    /// conn.add_address(
    ///     Ipv4Address::new("eth0", Ipv4Addr::new(192, 168, 1, 100), 24)
    /// ).await?;
    ///
    /// // Add IPv6 address
    /// conn.add_address(
    ///     Ipv6Address::new("eth0", "2001:db8::1".parse()?, 64)
    /// ).await?;
    /// ```
    pub async fn add_address<A: AddressConfig>(&self, config: A) -> Result<()> {
        let ifindex = self.resolve_interface(config.interface_ref()).await?;

        let mut builder = MessageBuilder::new(
            NlMsgType::RTM_NEWADDR,
            NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL,
        );

        config.write_add(&mut builder, ifindex)?;
        self.send_ack(builder)
            .await
            .map_err(|e| e.with_context("add_address"))
    }

    /// Delete an IP address from an interface.
    ///
    /// # Example
    ///
    /// ```ignore
    /// conn.del_address("eth0", IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)), 24).await?;
    /// ```
    #[tracing::instrument(level = "debug", skip_all, fields(method = "del_address"))]
    pub async fn del_address(
        &self,
        ifname: impl Into<InterfaceRef>,
        address: IpAddr,
        prefix_len: u8,
    ) -> Result<()> {
        let ifindex = self.resolve_interface(&ifname.into()).await?;
        self.del_address_by_index(ifindex, address, prefix_len)
            .await
    }

    /// Delete an IP address from an interface by index.
    ///
    /// This is namespace-safe as it doesn't require interface name resolution.
    #[tracing::instrument(level = "debug", skip_all, fields(method = "del_address_by_index"))]
    pub async fn del_address_by_index(
        &self,
        ifindex: u32,
        address: IpAddr,
        prefix_len: u8,
    ) -> Result<()> {
        match address {
            IpAddr::V4(addr) => {
                let config = Ipv4Address::with_index(ifindex, addr, prefix_len);
                self.del_address_config(config).await
            }
            IpAddr::V6(addr) => {
                let config = Ipv6Address::with_index(ifindex, addr, prefix_len);
                self.del_address_config(config).await
            }
        }
    }

    /// Add an IP address to an interface by index.
    ///
    /// This is namespace-safe as it doesn't require interface name resolution.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Get interface index via netlink
    /// let link = conn.get_link_by_name("eth0").await?.unwrap();
    ///
    /// // Add address by index
    /// conn.add_address_by_index(link.ifindex(), "192.168.1.100".parse()?, 24).await?;
    /// ```
    #[tracing::instrument(level = "debug", skip_all, fields(method = "add_address_by_index"))]
    pub async fn add_address_by_index(
        &self,
        ifindex: u32,
        address: IpAddr,
        prefix_len: u8,
    ) -> Result<()> {
        match address {
            IpAddr::V4(addr) => {
                let config = Ipv4Address::with_index(ifindex, addr, prefix_len);
                self.add_address(config).await
            }
            IpAddr::V6(addr) => {
                let config = Ipv6Address::with_index(ifindex, addr, prefix_len);
                self.add_address(config).await
            }
        }
    }

    /// Replace an IP address on an interface by index.
    ///
    /// This is namespace-safe as it doesn't require interface name resolution.
    #[tracing::instrument(level = "debug", skip_all, fields(method = "replace_address_by_index"))]
    pub async fn replace_address_by_index(
        &self,
        ifindex: u32,
        address: IpAddr,
        prefix_len: u8,
    ) -> Result<()> {
        match address {
            IpAddr::V4(addr) => {
                let config = Ipv4Address::with_index(ifindex, addr, prefix_len);
                self.replace_address(config).await
            }
            IpAddr::V6(addr) => {
                let config = Ipv6Address::with_index(ifindex, addr, prefix_len);
                self.replace_address(config).await
            }
        }
    }

    /// Add an IP address to an interface by name.
    ///
    /// This is a convenience method that resolves the interface name internally.
    ///
    /// # Example
    ///
    /// ```ignore
    /// conn.add_address_by_name("eth0", "192.168.1.100".parse()?, 24).await?;
    /// ```
    #[tracing::instrument(level = "debug", skip_all, fields(method = "add_address_by_name"))]
    pub async fn add_address_by_name(
        &self,
        ifname: impl Into<InterfaceRef>,
        address: IpAddr,
        prefix_len: u8,
    ) -> Result<()> {
        let ifindex = self.resolve_interface(&ifname.into()).await?;
        self.add_address_by_index(ifindex, address, prefix_len)
            .await
    }

    /// Replace an IP address on an interface by name.
    ///
    /// This is a convenience method that resolves the interface name internally.
    /// If the address exists, it will be updated; otherwise it will be created.
    ///
    /// # Example
    ///
    /// ```ignore
    /// conn.replace_address_by_name("eth0", "192.168.1.100".parse()?, 24).await?;
    /// ```
    #[tracing::instrument(level = "debug", skip_all, fields(method = "replace_address_by_name"))]
    pub async fn replace_address_by_name(
        &self,
        ifname: impl Into<InterfaceRef>,
        address: IpAddr,
        prefix_len: u8,
    ) -> Result<()> {
        let ifindex = self.resolve_interface(&ifname.into()).await?;
        self.replace_address_by_index(ifindex, address, prefix_len)
            .await
    }

    /// Delete an IPv4 address from an interface.
    #[tracing::instrument(level = "debug", skip_all, fields(method = "del_address_v4"))]
    pub async fn del_address_v4(
        &self,
        ifname: impl Into<InterfaceRef>,
        address: Ipv4Addr,
        prefix_len: u8,
    ) -> Result<()> {
        let ifindex = self.resolve_interface(&ifname.into()).await?;
        let config = Ipv4Address::with_index(ifindex, address, prefix_len);
        self.del_address_config(config).await
    }

    /// Delete an IPv6 address from an interface.
    #[tracing::instrument(level = "debug", skip_all, fields(method = "del_address_v6"))]
    pub async fn del_address_v6(
        &self,
        ifname: impl Into<InterfaceRef>,
        address: Ipv6Addr,
        prefix_len: u8,
    ) -> Result<()> {
        let ifindex = self.resolve_interface(&ifname.into()).await?;
        let config = Ipv6Address::with_index(ifindex, address, prefix_len);
        self.del_address_config(config).await
    }

    /// Delete an IP address using a typed config.
    pub async fn del_address_config<A: AddressConfig>(&self, config: A) -> Result<()> {
        let ifindex = self.resolve_interface(config.interface_ref()).await?;

        let mut builder = MessageBuilder::new(NlMsgType::RTM_DELADDR, NLM_F_REQUEST | NLM_F_ACK);

        config.write_delete(&mut builder, ifindex)?;
        self.send_ack(builder)
            .await
            .map_err(|e| e.with_context("del_address"))
    }

    /// Replace an IP address (add or update).
    ///
    /// This is like `add_address` but will update if the address exists.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Update address properties (lifetimes, etc.)
    /// conn.replace_address(
    ///     Ipv4Address::new("eth0", Ipv4Addr::new(192, 168, 1, 100), 24)
    ///         .preferred_lifetime(3600)
    ///         .valid_lifetime(7200)
    /// ).await?;
    /// ```
    pub async fn replace_address<A: AddressConfig>(&self, config: A) -> Result<()> {
        let ifindex = self.resolve_interface(config.interface_ref()).await?;

        let mut builder = MessageBuilder::new(
            NlMsgType::RTM_NEWADDR,
            NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_REPLACE,
        );

        config.write_replace(&mut builder, ifindex)?;
        self.send_ack(builder)
            .await
            .map_err(|e| e.with_context("replace_address"))
    }

    /// Flush all addresses from an interface.
    ///
    /// # Example
    ///
    /// ```ignore
    /// conn.flush_addresses("eth0").await?;
    /// ```
    #[tracing::instrument(level = "debug", skip_all, fields(method = "flush_addresses"))]
    pub async fn flush_addresses(&self, ifname: impl Into<InterfaceRef>) -> Result<()> {
        let ifindex = self.resolve_interface(&ifname.into()).await?;
        self.flush_addresses_by_index(ifindex).await
    }

    /// Flush all addresses from an interface by index.
    ///
    /// This is namespace-safe as it doesn't require interface name resolution.
    #[tracing::instrument(level = "debug", skip_all, fields(method = "flush_addresses_by_index"))]
    pub async fn flush_addresses_by_index(&self, ifindex: u32) -> Result<()> {
        let addresses = self.get_addresses_by_index(ifindex).await?;

        for addr in addresses {
            if let (Some(address), Some(prefix_len)) = (addr.address, Some(addr.prefix_len())) {
                // Skip loopback addresses on loopback interface (index 1 is typically lo)
                if ifindex == 1
                    && (address == IpAddr::V4(Ipv4Addr::LOCALHOST)
                        || address == IpAddr::V6(Ipv6Addr::LOCALHOST))
                {
                    continue;
                }

                if let Err(e) = self
                    .del_address_by_index(ifindex, address, prefix_len)
                    .await
                {
                    // Ignore "not found" errors (race condition)
                    if !e.is_not_found() {
                        return Err(e);
                    }
                }
            }
        }

        Ok(())
    }
}