Skip to content

Commit 6a003b4

Browse files
committed
fix net ip6 to ip4
Signed-off-by: Lan Liang <[email protected]>
1 parent d3f9979 commit 6a003b4

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

kclvm/runtime/src/net/mod.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,35 @@ pub extern "C-unwind" fn kclvm_net_to_IP4(
195195
kclvm_net_IP_string(ctx, args, kwargs)
196196
}
197197

198+
#[no_mangle]
199+
#[runtime_fn]
200+
pub extern "C-unwind" fn kclvm_net_IP6_to_IP4_string(
201+
ctx: *mut kclvm_context_t,
202+
args: *const kclvm_value_ref_t,
203+
kwargs: *const kclvm_value_ref_t,
204+
) -> *const kclvm_value_ref_t {
205+
let args = ptr_as_ref(args);
206+
let kwargs = ptr_as_ref(kwargs);
207+
let ctx = mut_ptr_as_ref(ctx);
208+
if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) {
209+
match Ipv6Addr::from_str(ip.as_ref()) {
210+
Ok(addr) => {
211+
if let Some(v4) = addr.to_ipv4() {
212+
let s = format!("{v4}");
213+
return ValueRef::str(s.as_ref()).into_raw(ctx);
214+
}
215+
let s = format!("can not parse {} ipv6 to ipv4!", ip);
216+
return ValueRef::str(s.as_ref()).into_raw(ctx);
217+
}
218+
Err(e) => {
219+
let s = format!("can not parse {} to ipv6:{}", ip, e);
220+
return ValueRef::str(s.as_ref()).into_raw(ctx);
221+
}
222+
}
223+
}
224+
panic!("IP_string() missing 1 required positional argument: 'ip'");
225+
}
226+
198227
// to_IP16(ip) -> int
199228

200229
#[no_mangle]
@@ -911,6 +940,29 @@ pub extern "C-unwind" fn kclvm_net_CIDR_netmask(
911940
mod test_net {
912941
use super::*;
913942

943+
#[test]
944+
#[allow(non_snake_case)]
945+
fn test_ip6_to_ip4() {
946+
let cases = [
947+
("::FFFF:192.168.1.10", "192.168.1.10"),
948+
(
949+
"::FFFF:192.168.x.10",
950+
"can not parse ::FFFF:192.168.x.10 to ipv6:invalid IPv6 address syntax",
951+
),
952+
];
953+
let mut ctx = Context::default();
954+
for (ip6, expected) in cases.iter() {
955+
unsafe {
956+
let actual = &*kclvm_net_IP6_to_IP4_string(
957+
&mut ctx,
958+
&ValueRef::list(Some(&[&ValueRef::str(ip6)])),
959+
&ValueRef::dict(None),
960+
);
961+
assert_eq!(&ValueRef::str(expected), actual, "{} positional", ip6,);
962+
}
963+
}
964+
}
965+
914966
#[test]
915967
fn test_split_host_port() {
916968
let cases = [
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import net
2+
3+
ip0 = net.to_IP4("::FFFF:192.168.1.10")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ip0: 192.168.1.10

0 commit comments

Comments
 (0)