Skip to content

Commit 55641c7

Browse files
authored
introduced Conversion for ipv4 to int
1 parent deab09f commit 55641c7

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

Rust_ipify_lib/src/ipify.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ pub fn get_ip4_string() -> Result<String, Box<dyn std::error::Error>> {
1212
Ok(body)
1313
}
1414

15+
pub fn get_ip4_i64() -> Result<i64, Box<dyn std::error::Error>> {
16+
let body = reqwest::blocking::get("https://api.ipify.org")?.text()?;
17+
let result = ip_to_int(body);
18+
Ok(result)
19+
}
20+
1521
pub fn get_ip_json() -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
1622
let body = reqwest::blocking::get("https://api.ipify.org?format=json")?
1723
.json::<HashMap<String, String>>()?;
@@ -22,3 +28,17 @@ pub fn get_ip_string() -> Result<String, Box<dyn std::error::Error>> {
2228
let body = reqwest::blocking::get("https://api.ipify.org")?.text()?;
2329
Ok(body)
2430
}
31+
32+
fn ip_to_int(ip :String) -> i64 {
33+
let mut result : i64 = 0;
34+
let splitted_ip : Vec<&str> = ip.split('.').collect();
35+
if splitted_ip.len() == 4 {
36+
let first_block : i64 = splitted_ip[0].parse::<i64>().unwrap();
37+
let second_block : i64 = splitted_ip[1].parse::<i64>().unwrap();
38+
let third_block : i64 = splitted_ip[2].parse::<i64>().unwrap();
39+
let fourth_block : i64 = splitted_ip[3].parse::<i64>().unwrap();
40+
41+
result = (first_block<<24)+(second_block<<16)+(third_block<<8)+(fourth_block<<0);
42+
}
43+
result
44+
}

Rust_ipify_lib_test/src/main.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
extern crate ipify_lib;
2-
use ipify_lib::ipify::get_ip_json;
3-
use ipify_lib::ipify::get_ip_string;
4-
use ipify_lib::ipify::get_ip4_json;
5-
use ipify_lib::ipify::get_ip4_string;
1+
extern crate rust_ipify;
2+
use rust_ipify::ipify::get_ip_json;
3+
use rust_ipify::ipify::get_ip_string;
4+
use rust_ipify::ipify::get_ip4_json;
5+
use rust_ipify::ipify::get_ip4_string;
6+
use rust_ipify::ipify::get_ip4_i64;
67
fn main() {
78
println!("inside main of test ");
89

@@ -31,4 +32,12 @@ fn main() {
3132
Ok(r) => println!("Result IP v4 ( String ): \n\t{:#?}\n", r),
3233
Err(e) => println!("error in request {:?}", e),
3334
}
35+
36+
let result_ip4_i64 = get_ip4_i64();
37+
match result_ip4_i64 {
38+
Ok(r) => println!("Result IP v4 ( i64 ): \n\t{:#?}\n", r),
39+
Err(e) => println!("error in request {:?}", e),
40+
}
41+
42+
3443
}

0 commit comments

Comments
 (0)