Skip to main content

nurtex_proxy/tools/
lookup.rs

1use serde::Deserialize;
2use tokio::io::{AsyncReadExt, AsyncWriteExt};
3
4use crate::Proxy;
5
6/// Структура первоначальной информации об IP
7#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
8struct LookupRawInfo {
9  pub ip: String,
10  pub hostname: String,
11  pub city: String,
12  pub region: String,
13  pub country: String,
14  pub loc: String,
15  pub org: String,
16  pub postal: String,
17  pub timezone: String,
18  pub readme: String,
19}
20
21/// Структура информации об IP
22#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
23pub struct LookupInfo {
24  pub ip: String,
25  pub hostname: String,
26  pub city: String,
27  pub region: String,
28  pub country: String,
29  pub location: String,
30  pub organization: String,
31  pub postal: String,
32  pub timezone: String,
33}
34
35/// Функция получения данных об IP адресе, используя `ipinfo.io`
36pub async fn lookup_proxy(proxy: &Proxy) -> Option<LookupInfo> {
37  let mut stream = match proxy.connect("ipinfo.io", 80).await {
38    Ok(s) => s,
39    Err(_) => return None,
40  };
41
42  let _ = stream.write_all(b"GET / HTTP/1.0\r\nHost: ipinfo.io\r\n\r\n").await;
43
44  let mut buf = Vec::new();
45  let _ = stream.read_to_end(&mut buf).await;
46
47  let data = match String::from_utf8(buf) {
48    Ok(s) => s,
49    Err(_) => String::new(),
50  };
51
52  let split_data = data.split("\n").collect::<Vec<&str>>();
53  let mut pretty_data = String::new();
54
55  // Можно просто пропустить заголовки
56  for (i, item) in split_data.iter().enumerate() {
57    if i < 7 {
58      continue;
59    }
60
61    pretty_data.push_str(*item);
62  }
63
64  let raw: LookupRawInfo = match serde_json::from_str(&pretty_data) {
65    Ok(info) => info,
66    Err(_) => return None,
67  };
68
69  Some(LookupInfo {
70    ip: raw.ip,
71    hostname: raw.hostname,
72    city: raw.city,
73    region: raw.region,
74    country: raw.country,
75    location: raw.loc,
76    organization: raw.org,
77    postal: raw.postal,
78    timezone: raw.timezone,
79  })
80}