vrl/stdlib/
ipv6_to_ipv4.rs

1use crate::compiler::prelude::*;
2use std::net::IpAddr;
3
4fn ipv6_to_ipv4(value: &Value) -> Resolved {
5    let ip = value
6        .try_bytes_utf8_lossy()?
7        .parse()
8        .map_err(|err| format!("unable to parse IP address: {err}"))?;
9    match ip {
10        IpAddr::V4(addr) => Ok(addr.to_string().into()),
11        IpAddr::V6(addr) => match addr.to_ipv4() {
12            Some(addr) => Ok(addr.to_string().into()),
13            None => Err(format!("IPV6 address {addr} is not compatible with IPV4").into()),
14        },
15    }
16}
17
18#[derive(Clone, Copy, Debug)]
19pub struct Ipv6ToIpV4;
20
21impl Function for Ipv6ToIpV4 {
22    fn identifier(&self) -> &'static str {
23        "ipv6_to_ipv4"
24    }
25
26    fn usage(&self) -> &'static str {
27        indoc! {"
28            Converts the `ip` to an IPv4 address. `ip` is returned unchanged if it's already an IPv4 address. If `ip` is
29            currently an IPv6 address then it needs to be IPv4 compatible, otherwise an error is thrown.
30        "}
31    }
32
33    fn category(&self) -> &'static str {
34        Category::Ip.as_ref()
35    }
36
37    fn internal_failure_reasons(&self) -> &'static [&'static str] {
38        &[
39            "`ip` is not a valid IP address.",
40            "`ip` is an IPv6 address that is not compatible with IPv4.",
41        ]
42    }
43
44    fn return_kind(&self) -> u16 {
45        kind::BYTES
46    }
47
48    fn return_rules(&self) -> &'static [&'static str] {
49        &[
50            "The `ip` is returned unchanged if it's already an IPv4 address. If it's an IPv6 address it must be IPv4
51compatible, otherwise an error is thrown.",
52        ]
53    }
54
55    fn parameters(&self) -> &'static [Parameter] {
56        const PARAMETERS: &[Parameter] = &[Parameter::required(
57            "value",
58            kind::BYTES,
59            "The IPv4-mapped IPv6 address to convert.",
60        )];
61        PARAMETERS
62    }
63
64    fn examples(&self) -> &'static [Example] {
65        &[example! {
66            title: "IPv6 to IPv4",
67            source: r#"ipv6_to_ipv4!("::ffff:192.168.0.1")"#,
68            result: Ok("192.168.0.1"),
69        }]
70    }
71
72    fn compile(
73        &self,
74        _state: &state::TypeState,
75        _ctx: &mut FunctionCompileContext,
76        arguments: ArgumentList,
77    ) -> Compiled {
78        let value = arguments.required("value");
79        Ok(Ipv6ToIpV4Fn { value }.as_expr())
80    }
81}
82
83#[derive(Debug, Clone)]
84struct Ipv6ToIpV4Fn {
85    value: Box<dyn Expression>,
86}
87
88impl FunctionExpression for Ipv6ToIpV4Fn {
89    fn resolve(&self, ctx: &mut Context) -> Resolved {
90        let value = self.value.resolve(ctx)?;
91        ipv6_to_ipv4(&value)
92    }
93
94    fn type_def(&self, _: &state::TypeState) -> TypeDef {
95        TypeDef::bytes().fallible()
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    test_function![
104        ipv6_to_ipv4 => Ipv6ToIpV4;
105
106        error {
107            args: func_args![value: "i am not an ipaddress"],
108            want: Err("unable to parse IP address: invalid IP address syntax".to_string()),
109            tdef: TypeDef::bytes().fallible(),
110        }
111
112        incompatible {
113            args: func_args![value: "2001:0db8:85a3::8a2e:0370:7334"],
114            want: Err("IPV6 address 2001:db8:85a3::8a2e:370:7334 is not compatible with IPV4".to_string()),
115            tdef: TypeDef::bytes().fallible(),
116        }
117
118        ipv4_compatible {
119            args: func_args![value: "::ffff:192.168.0.1"],
120            want: Ok(Value::from("192.168.0.1")),
121            tdef: TypeDef::bytes().fallible(),
122        }
123
124        ipv6 {
125            args: func_args![value: "0:0:0:0:0:ffff:c633:6410"],
126            want: Ok(Value::from("198.51.100.16")),
127            tdef: TypeDef::bytes().fallible(),
128        }
129
130        ipv4 {
131            args: func_args![value: "198.51.100.16"],
132            want: Ok(Value::from("198.51.100.16")),
133            tdef: TypeDef::bytes().fallible(),
134        }
135    ];
136}