Initial MeshPort SDK and cross-platform client
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
use anyhow::{Result, ensure};
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
pub async fn probe(
|
||||
target: SocketAddr,
|
||||
udp: bool,
|
||||
echo: bool,
|
||||
timeout: Duration,
|
||||
) -> Result<serde_json::Value> {
|
||||
ensure!(target.is_ipv4(), "IPv4 required");
|
||||
ensure!(!udp || echo, "UDP tests require a cooperating echo server");
|
||||
let started = Instant::now();
|
||||
let payload = b"MeshPort system socket echo v1";
|
||||
let bytes = tokio::time::timeout(timeout, async {
|
||||
if udp {
|
||||
let socket = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
|
||||
socket.connect(target).await?;
|
||||
socket.send(payload).await?;
|
||||
let mut bytes = [0; 2048];
|
||||
let n = socket.recv(&mut bytes).await?;
|
||||
ensure!(&bytes[..n] == payload, "echo data mismatch");
|
||||
Ok::<usize, anyhow::Error>(n)
|
||||
} else {
|
||||
let mut socket = tokio::net::TcpStream::connect(target).await?;
|
||||
if !echo {
|
||||
return Ok(0);
|
||||
}
|
||||
socket.write_all(payload).await?;
|
||||
let mut bytes = vec![0; payload.len()];
|
||||
socket.read_exact(&mut bytes).await?;
|
||||
ensure!(bytes == payload, "echo data mismatch");
|
||||
Ok(bytes.len())
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
Ok(
|
||||
serde_json::json!({"protocol": if udp {"UDP"} else {"TCP"}, "target": target.to_string(),
|
||||
"elapsed_ms": started.elapsed().as_secs_f64()*1000.0, "verified_bytes": bytes,
|
||||
"kind": if echo {"echo_roundtrip"} else {"tcp_connect"}, "socket_scope": "system"}),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user