hippox-drivers 0.3.5

🦛All indivisible atomic driver units in Hippox.
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
//! IP utilities module
//!
//! This module provides a collection of skills for working with IP addresses:
//! - `IpInfoDriver`: Query detailed geolocation and network information about IP addresses
//! - `IpValidateDriver`: Validate and classify IP addresses (public/private, IPv4/IPv6, etc.)
//! - `IpRangeDriver`: Calculate network ranges from CIDR notation
//! - `LocalIpDriver`: Get local IP addresses of the current machine
//!
//! # Examples
//!
//! ```
//! use std::collections::HashMap;
//! use serde_json::json;
//!
//! // Get info about an IP address
//! let skill = IpInfoDriver;
//! let mut params = HashMap::new();
//! params.insert("ip".to_string(), json!("8.8.8.8"));
//! // let result = skill.execute(&params).await?;
//! ```
use crate::{
    DriverCallback, DriverCategory, DriverContext, DriverError, DriverResult,
    types::{Driver, DriverParameter},
};
use regex::Regex;
use reqwest::Client;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tracing::{debug, info};
/// Driver for retrieving detailed geolocation and network information about an IP address.
///
/// This skill queries the ip-api.com service to obtain information such as:
/// - Geographic location (country, city, coordinates)
/// - ISP and organization details
/// - ASN (Autonomous System Number)
/// - Timezone information
///
/// Supports both IPv4 and IPv6 addresses. If no IP is provided, returns information
/// about the caller's public IP address.
///
/// # Example
/// ```ignore
/// let skill = IpInfoDriver;
/// let mut params = HashMap::new();
/// params.insert("ip".to_string(), json!("8.8.8.8"));
/// let result = skill.execute(&params).await?;
/// ```
#[derive(Debug)]
pub struct IpInfoDriver;
#[async_trait::async_trait]
impl Driver for IpInfoDriver {
    /// Returns the unique name of this driver
    fn name(&self) -> &str {
        "ip_info"
    }
    /// Returns a brief description of the driver's functionality
    fn description(&self) -> &str {
        "Get detailed information about an IP address including geolocation, ASN, ISP, and more"
    }
    /// Returns detailed usage guidance for LLMs
    fn usage_hint(&self) -> &str {
        "Use this skill when the user wants to find location, ISP, or other information about an IP address. \
         Supports both IPv4 and IPv6 addresses. If no IP is provided, returns information about the public IP."
    }
    /// Returns the parameter definitions for this driver
    fn parameters(&self) -> Vec<DriverParameter> {
        return vec![DriverParameter {
            name: "ip".to_string(),
            param_type: "string".to_string(),
            description: "IP address to lookup (IPv4 or IPv6). If omitted, returns your public IP".to_string(),
            required: false,
            default: None,
            example: Some(Value::String("8.8.8.8".to_string())),
            enum_values: None,
        }];
    }
    /// Returns an example call for this driver
    fn example_call(&self) -> DriverResult<Value> {
        return Ok(json!({
            "action": "ip_info",
            "parameters": {
                "ip": "8.8.8.8"
            }
        }));
    }
    /// Returns an example output from this driver
    fn example_output(&self) -> String {
        return "IP Information for 8.8.8.8:\nCountry: United States\nCity: Mountain View\nISP: Google LLC\nASN: AS15169\nLatitude: 37.4223\nLongitude: -122.0841\nTimezone: America/Los_Angeles".to_string();
    }
    /// Returns the category of this driver
    fn category(&self) -> DriverCategory {
        return DriverCategory::Network;
    }
    /// Executes the driver with the given parameters
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        _callback: Option<&dyn DriverCallback>,
        _context: Option<&DriverContext>,
    ) -> DriverResult<String> {
        debug!("Executing ip_info driver");
        let ip_param = parameters.get("ip").and_then(|v| v.as_str());
        let client = Client::builder()
            .timeout(std::time::Duration::from_secs(10))
            .build()
            .map_err(|e| DriverError::execution(format!("Failed to build HTTP client: {}", e)))?;
        let url = if let Some(ip) = ip_param { format!("http://ip-api.com/json/{}", ip) } else { "http://ip-api.com/json".to_string() };
        info!("IP info query: {}", url);
        let response = client
            .get(&url)
            .header("User-Agent", "curl/7.68.0")
            .send()
            .await
            .map_err(|e| DriverError::execution(format!("Failed to query IP info: {}", e)))?;
        let text = response.text().await.map_err(|e| DriverError::execution(format!("Failed to read response: {}", e)))?;
        let data: serde_json::Value = serde_json::from_str(&text).map_err(|e| DriverError::execution(format!("Failed to parse response: {}", e)))?;
        if data.get("status").and_then(|s| s.as_str()) == Some("fail") {
            let msg = data.get("message").and_then(|m| m.as_str()).unwrap_or("Unknown error");
            info!("IP info query failed: {}", msg);
            return Ok(format!("Failed to get IP info: {}", msg));
        }
        let ip_addr = ip_param.unwrap_or_else(|| data.get("query").and_then(|q| q.as_str()).unwrap_or("Unknown"));
        info!("IP info retrieved for {}", ip_addr);
        let mut result = String::new();
        result.push_str(&format!("IP Information for {}:\n", ip_addr));
        result.push_str(&format!("Country: {}\n", data.get("country").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("Country Code: {}\n", data.get("countryCode").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("Region: {}\n", data.get("regionName").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("City: {}\n", data.get("city").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("ZIP Code: {}\n", data.get("zip").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("Latitude: {}\n", data.get("lat").and_then(|v| v.as_f64()).unwrap_or(0.0)));
        result.push_str(&format!("Longitude: {}\n", data.get("lon").and_then(|v| v.as_f64()).unwrap_or(0.0)));
        result.push_str(&format!("ISP: {}\n", data.get("isp").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("Organization: {}\n", data.get("org").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("AS: {}\n", data.get("as").and_then(|v| v.as_str()).unwrap_or("N/A")));
        result.push_str(&format!("Timezone: {}\n", data.get("timezone").and_then(|v| v.as_str()).unwrap_or("N/A")));
        return Ok(result);
    }
}
/// Driver for validating IP addresses and classifying their type.
///
/// This skill parses and validates IP address strings, then provides detailed
/// classification information including:
/// - IP version (IPv4 or IPv6)
/// - Address classification (public, private, loopback, multicast, etc.)
/// - Special address detection (broadcast, documentation, link-local)
///
/// # Example
/// ```ignore
/// let skill = IpValidateDriver;
/// let mut params = HashMap::new();
/// params.insert("ip".to_string(), json!("192.168.1.1"));
/// let result = skill.execute(&params).await?;
/// ```
#[derive(Debug)]
pub struct IpValidateDriver;
#[async_trait::async_trait]
impl Driver for IpValidateDriver {
    /// Returns the unique name of this driver
    fn name(&self) -> &str {
        "ip_validate"
    }
    /// Returns a brief description of the driver's functionality
    fn description(&self) -> &str {
        "Validate IP addresses and provide information about their type (public/private, IPv4/IPv6, etc.)"
    }
    /// Returns detailed usage guidance for LLMs
    fn usage_hint(&self) -> &str {
        "Use this skill to check if an IP address is valid and classify it (public, private, loopback, multicast, etc.)"
    }
    /// Returns the parameter definitions for this driver
    fn parameters(&self) -> Vec<DriverParameter> {
        return vec![DriverParameter {
            name: "ip".to_string(),
            param_type: "string".to_string(),
            description: "IP address to validate".to_string(),
            required: true,
            default: None,
            example: Some(Value::String("192.168.1.1".to_string())),
            enum_values: None,
        }];
    }
    /// Returns an example call for this driver
    fn example_call(&self) -> DriverResult<Value> {
        return Ok(json!({
            "action": "ip_validate",
            "parameters": {
                "ip": "10.0.0.1"
            }
        }));
    }
    /// Returns an example output from this driver
    fn example_output(&self) -> String {
        return "IP Address: 10.0.0.1\nType: IPv4\nClassification: Private (RFC 1918)\nValid: Yes\nLoopback: No\nMulticast: No".to_string();
    }
    /// Returns the category of this driver
    fn category(&self) -> DriverCategory {
        return DriverCategory::Network;
    }
    /// Executes the driver with the given parameters
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        _callback: Option<&dyn DriverCallback>,
        _context: Option<&DriverContext>,
    ) -> DriverResult<String> {
        debug!("Executing ip_validate driver");
        let ip_str = parameters.get("ip").and_then(|v| v.as_str()).ok_or_else(|| DriverError::missing_parameter("ip"))?;
        info!("Validating IP: {}", ip_str);
        match ip_str.parse::<IpAddr>() {
            Ok(ip) => {
                let mut result = format!("IP Address: {}\n", ip);
                result.push_str(&format!("Type: {}\n", if ip.is_ipv4() { "IPv4" } else { "IPv6" }));
                let classification = classify_ip(&ip);
                result.push_str(&format!("Classification: {}\n", classification));
                result.push_str("Valid: Yes\n");
                result.push_str(&format!("Loopback: {}\n", ip.is_loopback()));
                result.push_str(&format!("Multicast: {}\n", ip.is_multicast()));
                if let IpAddr::V4(ipv4) = ip {
                    result.push_str(&format!("Broadcast: {}\n", ipv4.is_broadcast()));
                    result.push_str(&format!("Documentation: {}\n", is_documentation_ipv4(&ipv4)));
                }
                info!("IP validation successful: {}", ip_str);
                return Ok(result);
            }
            Err(e) => {
                info!("IP validation failed: {}", e);
                return Ok(format!("Invalid IP address: {}\nError: {}", ip_str, e));
            }
        }
    }
}
/// Driver for calculating IP address ranges from CIDR notation.
///
/// This skill computes network details from a CIDR (Classless Inter-Domain Routing)
/// notation string, providing:
/// - Network address
/// - Subnet mask
/// - Wildcard mask
/// - First and last usable IP addresses
/// - Broadcast address
/// - Total number of usable hosts
///
/// # Example
/// ```ignore
/// let skill = IpRangeDriver;
/// let mut params = HashMap::new();
/// params.insert("cidr".to_string(), json!("192.168.1.0/24"));
/// let result = skill.execute(&params).await?;
/// ```
#[derive(Debug)]
pub struct IpRangeDriver;
#[async_trait::async_trait]
impl Driver for IpRangeDriver {
    /// Returns the unique name of this driver
    fn name(&self) -> &str {
        "ip_range"
    }
    /// Returns a brief description of the driver's functionality
    fn description(&self) -> &str {
        "Calculate IP address ranges from CIDR notation or subnet mask"
    }
    /// Returns detailed usage guidance for LLMs
    fn usage_hint(&self) -> &str {
        "Use this skill when you need to calculate network ranges, subnet details, or CIDR information"
    }
    /// Returns the parameter definitions for this driver
    fn parameters(&self) -> Vec<DriverParameter> {
        return vec![DriverParameter {
            name: "cidr".to_string(),
            param_type: "string".to_string(),
            description: "CIDR notation (e.g., 192.168.1.0/24) or IP with subnet mask".to_string(),
            required: true,
            default: None,
            example: Some(Value::String("192.168.1.0/24".to_string())),
            enum_values: None,
        }];
    }
    /// Returns an example call for this driver
    fn example_call(&self) -> DriverResult<Value> {
        return Ok(json!({
            "action": "ip_range",
            "parameters": {
                "cidr": "10.0.0.0/16"
            }
        }));
    }
    /// Returns an example output from this driver
    fn example_output(&self) -> String {
        return "CIDR: 10.0.0.0/16\nNetwork: 10.0.0.0\nSubnet Mask: 255.255.0.0\nWildcard: 0.0.255.255\nFirst IP: 10.0.0.1\nLast IP: 10.0.255.254\nBroadcast: 10.0.255.255\nTotal Hosts: 65534".to_string();
    }
    /// Returns the category of this driver
    fn category(&self) -> DriverCategory {
        return DriverCategory::Network;
    }
    /// Executes the driver with the given parameters
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        _callback: Option<&dyn DriverCallback>,
        _context: Option<&DriverContext>,
    ) -> DriverResult<String> {
        debug!("Executing ip_range driver");
        let cidr = parameters.get("cidr").and_then(|v| v.as_str()).ok_or_else(|| DriverError::missing_parameter("cidr"))?;
        info!("Calculating IP range for CIDR: {}", cidr);
        let re = Regex::new(r"^(\d+\.\d+\.\d+\.\d+)/(\d+)$").map_err(|e| DriverError::execution(format!("Invalid regex: {}", e)))?;
        let caps = match re.captures(cidr) {
            Some(caps) => caps,
            None => return Ok(format!("Invalid CIDR format: {}", cidr)),
        };
        let ip_str = caps.get(1).unwrap().as_str();
        let prefix_len: u32 = caps.get(2).unwrap().as_str().parse().map_err(|e| DriverError::execution(format!("Invalid prefix length: {}", e)))?;
        if prefix_len > 32 {
            return Err(DriverError::execution("Prefix length must be between 0 and 32"));
        }
        let ip: u32 = ip_str.parse::<Ipv4Addr>().map_err(|e| DriverError::execution(format!("Invalid IP address: {}", e)))?.into();
        let mask = !((1 << (32 - prefix_len)) - 1);
        let network = ip & mask;
        let broadcast = network | !mask;
        let first_host = if network == broadcast { network } else { network + 1 };
        let last_host = if network == broadcast { broadcast } else { broadcast - 1 };
        let total_hosts = if network == broadcast { 1 } else { broadcast - network - 1 };
        info!("IP range calculated: network={}, broadcast={}, hosts={}", Ipv4Addr::from(network), Ipv4Addr::from(broadcast), total_hosts);
        return Ok(format!(
            "CIDR: {}\nNetwork: {}\nSubnet Mask: {}\nWildcard: {}\nFirst IP: {}\nLast IP: {}\nBroadcast: {}\nTotal Hosts: {}",
            cidr,
            Ipv4Addr::from(network),
            Ipv4Addr::from(mask),
            Ipv4Addr::from(!mask),
            Ipv4Addr::from(first_host),
            Ipv4Addr::from(last_host),
            Ipv4Addr::from(broadcast),
            total_hosts
        ));
    }
}
/// Driver for retrieving local IP addresses of the current machine.
///
/// This skill enumerates all network interfaces on the local system and returns
/// their IP addresses. It can filter results by IP version (IPv4 only, IPv6 only,
/// or all addresses).
///
/// # Example
/// ```ignore
/// let skill = LocalIpDriver;
/// let mut params = HashMap::new();
/// params.insert("type".to_string(), json!("ipv4"));
/// let result = skill.execute(&params).await?;
/// ```
#[derive(Debug)]
pub struct LocalIpDriver;
#[async_trait::async_trait]
impl Driver for LocalIpDriver {
    /// Returns the unique name of this driver
    fn name(&self) -> &str {
        "local_ip"
    }
    /// Returns a brief description of the driver's functionality
    fn description(&self) -> &str {
        "Get local IP addresses of the current machine (both IPv4 and IPv6)"
    }
    /// Returns detailed usage guidance for LLMs
    fn usage_hint(&self) -> &str {
        "Use this skill when you need to know the local IP addresses of the current system"
    }
    /// Returns the parameter definitions for this driver
    fn parameters(&self) -> Vec<DriverParameter> {
        return vec![DriverParameter {
            name: "type".to_string(),
            param_type: "string".to_string(),
            description: "IP type to return: 'all', 'ipv4', or 'ipv6'".to_string(),
            required: false,
            default: Some(Value::String("all".to_string())),
            example: Some(Value::String("ipv4".to_string())),
            enum_values: Some(vec!["all".to_string(), "ipv4".to_string(), "ipv6".to_string()]),
        }];
    }
    /// Returns an example call for this driver
    fn example_call(&self) -> DriverResult<Value> {
        return Ok(json!({
            "action": "local_ip",
            "parameters": {
                "type": "all"
            }
        }));
    }
    /// Returns an example output from this driver
    fn example_output(&self) -> String {
        return "Local IP addresses:\nIPv4: 192.168.1.100\nIPv6: fe80::1%eth0\nLoopback: 127.0.0.1".to_string();
    }
    /// Returns the category of this driver
    fn category(&self) -> DriverCategory {
        return DriverCategory::Network;
    }
    /// Executes the driver with the given parameters
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        _callback: Option<&dyn DriverCallback>,
        _context: Option<&DriverContext>,
    ) -> DriverResult<String> {
        debug!("Executing local_ip driver");
        let ip_type = parameters.get("type").and_then(|v| v.as_str()).unwrap_or("all");
        info!("Getting local IP addresses, type={}", ip_type);
        let mut result = String::from("Local IP addresses:\n");
        let interfaces =
            local_ip_address::list_afinet_netifas().map_err(|e| DriverError::execution(format!("Failed to list network interfaces: {}", e)))?;
        let mut found = false;
        for (name, ip) in interfaces {
            match ip {
                IpAddr::V4(ipv4) => {
                    if ip_type == "all" || ip_type == "ipv4" {
                        if !ipv4.is_loopback() {
                            result.push_str(&format!("  {} ({}): {}\n", name, "IPv4", ipv4));
                            found = true;
                        }
                    }
                }
                IpAddr::V6(ipv6) => {
                    if ip_type == "all" || ip_type == "ipv6" {
                        if !ipv6.is_loopback() {
                            result.push_str(&format!("  {} ({}): {}\n", name, "IPv6", ipv6));
                            found = true;
                        }
                    }
                }
            }
        }
        result.push_str(&format!("  Loopback: 127.0.0.1\n"));
        if !found && ip_type != "loopback" {
            result.push_str("  No non-loopback addresses found\n");
            info!("No non-loopback IP addresses found");
        } else {
            info!("Local IP addresses retrieved successfully");
        }
        return Ok(result);
    }
}
/// Classifies an IP address into a human-readable category.
///
/// For IPv4 addresses, this function identifies:
/// - Private addresses (RFC 1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
/// - Loopback (127.0.0.0/8)
/// - Multicast (224.0.0.0/4)
/// - Broadcast (255.255.255.255)
/// - Documentation/reserved addresses (TEST-NET-1/2/3, etc.)
/// - Public addresses (everything else)
///
/// For IPv6 addresses, it identifies:
/// - Loopback (::1)
/// - Multicast (ff00::/8)
/// - Unique Local Addresses (ULA, fc00::/7)
/// - Link Local addresses (fe80::/10)
/// - Global Unicast addresses (everything else)
///
/// # Arguments
/// * `ip` - The IP address to classify
///
/// # Returns
/// A string describing the address classification
fn classify_ip(ip: &IpAddr) -> String {
    match ip {
        IpAddr::V4(ipv4) => {
            if ipv4.is_private() {
                "Private (RFC 1918)".to_string()
            } else if ipv4.is_loopback() {
                "Loopback".to_string()
            } else if ipv4.is_multicast() {
                "Multicast".to_string()
            } else if ipv4.is_broadcast() {
                "Broadcast".to_string()
            } else if is_documentation_ipv4(ipv4) {
                "Documentation/Reserved".to_string()
            } else {
                "Public".to_string()
            }
        }
        IpAddr::V6(ipv6) => {
            if ipv6.is_loopback() {
                "Loopback".to_string()
            } else if ipv6.is_multicast() {
                "Multicast".to_string()
            } else if ipv6.is_unique_local() {
                "Unique Local (ULA)".to_string()
            } else if is_link_local(ipv6) {
                "Link Local".to_string()
            } else {
                "Global Unicast".to_string()
            }
        }
    }
}
/// Checks if an IPv4 address falls within documentation or reserved ranges.
///
/// These ranges are reserved for documentation, examples, and testing purposes:
/// - 192.0.2.0/24 (TEST-NET-1)
/// - 198.51.100.0/24 (TEST-NET-2)
/// - 203.0.113.0/24 (TEST-NET-3)
/// - 192.88.99.0/24 (6to4 relay anycast)
/// - 198.18.0.0/15 (Benchmark testing)
///
/// # Arguments
/// * `ip` - The IPv4 address to check
///
/// # Returns
/// `true` if the address is in a documentation/reserved range, `false` otherwise
fn is_documentation_ipv4(ip: &Ipv4Addr) -> bool {
    let octets = ip.octets();
    match octets {
        [192, 0, 2, _] => true,    // TEST-NET-1
        [198, 51, 100, _] => true, // TEST-NET-2
        [203, 0, 113, _] => true,  // TEST-NET-3
        [192, 88, 99, _] => true,  // 6to4 relay anycast
        [198, 18, 0, _] => true,   // Benchmarking
        _ => false,
    }
}
/// Checks if an IPv6 address is a link-local address.
///
/// Link-local addresses have the prefix fe80::/10, meaning the first 10 bits
/// are 1111111010. In segment notation, the first segment must be 0xfe80
/// and the second segment's first 6 bits must be 0.
///
/// # Arguments
/// * `ip` - The IPv6 address to check
///
/// # Returns
/// `true` if the address is link-local, `false` otherwise
fn is_link_local(ip: &Ipv6Addr) -> bool {
    let segments = ip.segments();
    segments[0] == 0xfe80 && (segments[1] & 0xffc0) == 0
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr};
    /// Test IP address classification for various IPv4 addresses
    #[test]
    fn test_classify_ipv4() {
        // Private addresses (RFC 1918)
        let private_ips =
            vec![Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(172, 16, 0, 1), Ipv4Addr::new(172, 31, 255, 255), Ipv4Addr::new(192, 168, 1, 1)];
        for ip in private_ips {
            assert_eq!(classify_ip(&IpAddr::V4(ip)), "Private (RFC 1918)");
        }
        // Loopback address
        let loopback = Ipv4Addr::new(127, 0, 0, 1);
        assert_eq!(classify_ip(&IpAddr::V4(loopback)), "Loopback");
        // Multicast address
        let multicast = Ipv4Addr::new(224, 0, 0, 1);
        assert_eq!(classify_ip(&IpAddr::V4(multicast)), "Multicast");
        // Broadcast address
        let broadcast = Ipv4Addr::new(255, 255, 255, 255);
        assert_eq!(classify_ip(&IpAddr::V4(broadcast)), "Broadcast");
        // Documentation/Reserved addresses
        let doc_ips = vec![
            Ipv4Addr::new(192, 0, 2, 1),    // TEST-NET-1
            Ipv4Addr::new(198, 51, 100, 1), // TEST-NET-2
            Ipv4Addr::new(203, 0, 113, 1),  // TEST-NET-3
            Ipv4Addr::new(192, 88, 99, 1),  // 6to4 relay
            Ipv4Addr::new(198, 18, 0, 1),   // Benchmarking
        ];
        for ip in doc_ips {
            assert_eq!(classify_ip(&IpAddr::V4(ip)), "Documentation/Reserved");
        }
        // Public addresses
        let public_ips = vec![
            Ipv4Addr::new(8, 8, 8, 8),        // Google DNS
            Ipv4Addr::new(1, 1, 1, 1),        // Cloudflare DNS
            Ipv4Addr::new(208, 67, 222, 222), // OpenDNS
        ];
        for ip in public_ips {
            assert_eq!(classify_ip(&IpAddr::V4(ip)), "Public");
        }
    }
    /// Test IP address classification for various IPv6 addresses
    #[test]
    fn test_classify_ipv6() {
        // Loopback
        let loopback = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
        assert_eq!(classify_ip(&IpAddr::V6(loopback)), "Loopback");
        // Multicast
        let multicast = Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 1);
        assert_eq!(classify_ip(&IpAddr::V6(multicast)), "Multicast");
        // Unique Local Address (ULA)
        let ula = Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 1);
        assert_eq!(classify_ip(&IpAddr::V6(ula)), "Unique Local (ULA)");
        // Link Local
        let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
        assert_eq!(classify_ip(&IpAddr::V6(link_local)), "Link Local");
        // Global Unicast (Google DNS)
        let global = Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888);
        assert_eq!(classify_ip(&IpAddr::V6(global)), "Global Unicast");
    }
    /// Test CIDR range calculations for various subnet sizes
    #[test]
    fn test_cidr_calculations() {
        // /24 network
        let ip: u32 = Ipv4Addr::new(192, 168, 1, 0).into();
        let prefix_len = 24;
        let mask = !((1 << (32 - prefix_len)) - 1);
        let network = ip & mask;
        let broadcast = network | !mask;
        let total_hosts = broadcast - network - 1;
        assert_eq!(network, u32::from(Ipv4Addr::new(192, 168, 1, 0)));
        assert_eq!(broadcast, u32::from(Ipv4Addr::new(192, 168, 1, 255)));
        assert_eq!(total_hosts, 254);
        // /16 network
        let ip: u32 = Ipv4Addr::new(10, 0, 0, 0).into();
        let prefix_len = 16;
        let mask = !((1 << (32 - prefix_len)) - 1);
        let network = ip & mask;
        let broadcast = network | !mask;
        let total_hosts = broadcast - network - 1;
        assert_eq!(network, u32::from(Ipv4Addr::new(10, 0, 0, 0)));
        assert_eq!(broadcast, u32::from(Ipv4Addr::new(10, 0, 255, 255)));
        assert_eq!(total_hosts, 65534);
        // /32 network (single host)
        let ip: u32 = Ipv4Addr::new(192, 168, 1, 100).into();
        let prefix_len = 32;
        let mask = !((1 << (32 - prefix_len)) - 1);
        let network = ip & mask;
        let broadcast = network | !mask;
        let total_hosts = if network == broadcast { 1 } else { broadcast - network - 1 };
        assert_eq!(network, u32::from(Ipv4Addr::new(192, 168, 1, 100)));
        assert_eq!(broadcast, u32::from(Ipv4Addr::new(192, 168, 1, 100)));
        assert_eq!(total_hosts, 1);
    }
    /// Test link-local address detection for IPv6
    #[test]
    fn test_link_local_detection() {
        let valid = vec![
            Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
            Ipv6Addr::new(0xfe80, 0x1234, 0, 0, 0, 0, 0, 1),
            Ipv6Addr::new(0xfe80, 0xffff, 0, 0, 0, 0, 0, 1),
        ];
        for ip in valid {
            assert!(is_link_local(&ip), "Expected {:?} to be link-local", ip);
        }
        let invalid = vec![
            Ipv6Addr::new(0xfe90, 0, 0, 0, 0, 0, 0, 1),      // Wrong prefix
            Ipv6Addr::new(0xfe00, 0, 0, 0, 0, 0, 0, 1),      // Wrong prefix
            Ipv6Addr::new(0x2001, 0x4860, 0, 0, 0, 0, 0, 1), // Global unicast
            Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 1),      // ULA
        ];
        for ip in invalid {
            assert!(!is_link_local(&ip), "Expected {:?} not to be link-local", ip);
        }
    }
    /// Test IP validation for valid and invalid addresses
    #[test]
    fn test_ip_validation() {
        // Valid IPv4 addresses
        let valid_v4 = vec!["8.8.8.8", "192.168.1.1", "10.0.0.1", "127.0.0.1"];
        for ip in valid_v4 {
            assert!(ip.parse::<IpAddr>().is_ok(), "Expected {} to be valid", ip);
        }
        // Invalid IPv4 addresses
        let invalid_v4 = vec!["256.1.1.1", "1.1.1", "abc.def.ghi.jkl", "192.168.1.256"];
        for ip in invalid_v4 {
            assert!(ip.parse::<IpAddr>().is_err(), "Expected {} to be invalid", ip);
        }
        // Valid IPv6 addresses
        let valid_v6 = vec!["::1", "2001:4860:4860::8888", "fe80::1", "fc00::1", "ff00::1"];
        for ip in valid_v6 {
            assert!(ip.parse::<IpAddr>().is_ok(), "Expected {} to be valid", ip);
        }
        // Invalid IPv6 addresses
        let invalid_v6 = vec![":::", "2001:4860:4860::8888::1", "fe80:1"];
        for ip in invalid_v6 {
            assert!(ip.parse::<IpAddr>().is_err(), "Expected {} to be invalid", ip);
        }
    }
    /// Test IP info driver with a known public IP
    #[tokio::test]
    async fn test_ip_info_driver() {
        let skill = IpInfoDriver;
        let mut params = HashMap::new();
        params.insert("ip".to_string(), json!("8.8.8.8"));
        let result = skill.execute(&params, None, None).await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("IP Information for 8.8.8.8:"));
        assert!(output.contains("Country:"));
        assert!(output.contains("ISP:"));
        assert!(output.contains("AS:"));
    }
    /// Test local IP driver
    #[tokio::test]
    async fn test_local_ip_driver() {
        let skill = LocalIpDriver;
        let mut params = HashMap::new();
        params.insert("type".to_string(), json!("all"));
        let result = skill.execute(&params, None, None).await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Local IP addresses:"));
        assert!(output.contains("Loopback: 127.0.0.1"));
    }
    /// Test IP range driver
    #[tokio::test]
    async fn test_ip_range_driver() {
        let skill = IpRangeDriver;
        let mut params = HashMap::new();
        params.insert("cidr".to_string(), json!("192.168.1.0/24"));
        let result = skill.execute(&params, None, None).await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("CIDR: 192.168.1.0/24"));
        assert!(output.contains("Network: 192.168.1.0"));
        assert!(output.contains("Broadcast: 192.168.1.255"));
        assert!(output.contains("Total Hosts: 254"));
    }
    /// Test IP range driver with invalid input
    #[tokio::test]
    async fn test_ip_range_driver_invalid() {
        let skill = IpRangeDriver;
        let mut params = HashMap::new();
        params.insert("cidr".to_string(), json!("invalid"));
        let result = skill.execute(&params, None, None).await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Invalid CIDR format"));
    }
}