Skip to content

Commit 48ec5a0

Browse files
committed
支持结果排序
1 parent 0b40aca commit 48ec5a0

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/main.rs

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
use futures::future::join_all;
22
use indicatif::ProgressBar;
3-
use std::io::Write;
3+
use std::io::{BufRead, Write};
44
use std::sync::Arc;
55
use surge_ping::{Client, Config, IcmpPacket, PingIdentifier, PingSequence};
66
use tokio::io::AsyncWriteExt;
77
mod utils;
88
use rand::random;
99
use std::time::Duration;
10-
1110
async fn perform_first_stage() -> Result<(), Box<dyn std::error::Error>> {
1211
let cloudflare_ipv4_addresses = utils::get_all_ipv4().await?;
1312
let mut tasks = Vec::new();
@@ -103,7 +102,7 @@ async fn perform_second_stage() -> Result<(), Box<dyn std::error::Error>> {
103102
Ok((IcmpPacket::V6(_packet), _duration)) => {}
104103
Err(_) => {
105104
let mut result_line = String::from(ipv4_address);
106-
result_line.push_str(" timeout\n");
105+
result_line.push_str(" 999999\n");
107106
let mut file_handle = ping_result_file_clone.lock().await;
108107
file_handle.write(result_line.as_bytes()).unwrap();
109108
}
@@ -121,6 +120,31 @@ async fn perform_second_stage() -> Result<(), Box<dyn std::error::Error>> {
121120
ping_result_file_lock.lock().await.sync_all().unwrap();
122121
return Ok(());
123122
}
123+
fn sort_ping_results() -> std::result::Result<(), Box<dyn std::error::Error>> {
124+
let file = std::fs::File::open("result/ping_ip.txt")?;
125+
let reader = std::io::BufReader::new(file);
126+
127+
let mut ping_results: Vec<(String, u64)> = Vec::new();
128+
129+
for line in reader.lines() {
130+
let line = line?;
131+
let parts: Vec<&str> = line.split_whitespace().collect();
132+
if parts.len() == 2 {
133+
let ip = parts[0].to_owned();
134+
let ms = parts[1].parse::<u64>().unwrap_or(0);
135+
ping_results.push((ip, ms));
136+
}
137+
}
138+
139+
ping_results.sort_by(|a, b| a.1.cmp(&b.1));
140+
141+
let mut sorted_file = std::fs::File::create("result/sorted_ping_ip.txt")?;
142+
for (ip, ms) in ping_results {
143+
writeln!(sorted_file, "{} {}", ip, ms)?;
144+
}
145+
146+
Ok(())
147+
}
124148

125149
#[tokio::main]
126150
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -129,5 +153,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
129153
perform_first_stage().await?;
130154
println!("Performing second stage");
131155
perform_second_stage().await?;
156+
println!("Sorting results");
157+
sort_ping_results()?;
158+
println!("Done");
132159
return Ok(());
133160
}

0 commit comments

Comments
 (0)