1#[cfg(feature = "net")]
2use std::net::IpAddr;
3
4#[cfg(feature = "net")]
5use sysinfo::Networks;
6#[derive(Debug)]
7#[cfg(feature = "net")]
8pub struct IpAddress {
9 pub interface: String,
10 pub ip: IpAddr,
11 pub prefix: u8,
12}
13
14#[cfg(feature = "net")]
16pub fn list_ip_address() -> Vec<IpAddress> {
17 let networks = Networks::new_with_refreshed_list();
18 let mut address = Vec::new();
19 for (name, network) in networks.iter() {
20 for ip in network.ip_networks() {
21 address.push(IpAddress {
22 interface: name.clone(),
23 ip: ip.addr,
24 prefix: ip.prefix,
25 });
26 }
27 }
28 address
29}
30
31#[cfg(feature = "net")]
33pub fn block_download_file(
34 url: &str,
35 save_path: &str,
36 callback: Option<fn(cur: u64, total: u64)>,
37) -> Result<(), String> {
38 use reqwest::{blocking::Client, header::CONTENT_LENGTH};
39 use std::{
40 fs::File,
41 io::{Read, Write},
42 path::Path,
43 };
44 let client = Client::new();
45 let response = client.head(url).send().map_err(|e| e.to_string())?; let total_size = if let Some(size) = response.headers().get(CONTENT_LENGTH) {
48 size.to_str()
49 .map_err(|e| e.to_string())?
50 .parse::<u64>()
51 .unwrap_or(0)
52 } else {
53 0
54 };
55
56 let mut response = client.get(url).send().map_err(|e| e.to_string())?; let mut file = File::create(Path::new(save_path)).map_err(|e| e.to_string())?;
58
59 let mut downloaded: u64 = 0;
60 let mut buffer = [0; 8192]; while let Ok(n) = response.read(&mut buffer) {
62 if n == 0 {
63 break;
64 }
65 file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
66 downloaded += n as u64;
67 if let Some(callback) = callback {
68 callback(downloaded, total_size);
69 }
70 }
71 Ok(())
72}
73
74#[cfg(feature = "net")]
76pub fn block_download_string(url: &str) -> Result<String, String> {
77 use reqwest::blocking::Client;
78 let client = Client::new();
79 let response = client.get(url).send().map_err(|e| e.to_string())?; let data = response.bytes().map_err(|e| e.to_string())?;
81 let data = String::from_utf8(data.to_vec()).map_err(|e| e.to_string())?;
82 Ok(data)
83}
84
85#[test]
86#[cfg(feature = "net")]
87fn test_list_ip_address() {
88 let ret = list_ip_address();
89 println!("{:#?}", ret);
90}