Skip to content

Commit

Permalink
g3-socket: add tcp connect testcase
Browse files Browse the repository at this point in the history
  • Loading branch information
zh-jq-b committed Oct 23, 2024
1 parent 4495152 commit c79d126
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
3 changes: 3 additions & 0 deletions lib/g3-socket/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ socket2 = { version = "0.5", features = ["all"] }
libc.workspace = true
fastrand.workspace = true
g3-types.workspace = true

[dev-dependencies]
tokio = { workspace = true, features = ["macros", "rt"] }
32 changes: 32 additions & 0 deletions lib/g3-socket/src/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,35 @@ pub fn new_socket_to(
let socket = new_std_socket_to(peer_ip, bind, keepalive, misc_opts, default_set_nodelay)?;
Ok(TcpSocket::from_std_stream(socket))
}

#[cfg(test)]
mod tests {
use super::*;
use std::net::{Ipv4Addr, SocketAddr};

#[tokio::test]
async fn listen_connect() {
let listen_config =
TcpListenConfig::new(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0));
let listen_socket = new_listen_to(&listen_config).unwrap();
let listen_addr = listen_socket.local_addr().unwrap();

let accept_task = tokio::spawn(async move {
let (_stream, accepted_addr) = listen_socket.accept().await.unwrap();
accepted_addr
});

let connect_sock = new_socket_to(
listen_addr.ip(),
&BindAddr::None,
&TcpKeepAliveConfig::default(),
&TcpMiscSockOpts::default(),
true,
)
.unwrap();
let connected_stream = connect_sock.connect(listen_addr).await.unwrap();
let connect_addr = connected_stream.local_addr().unwrap();
let accepted_addr = accept_task.await.unwrap();
assert_eq!(connect_addr, accepted_addr);
}
}
10 changes: 7 additions & 3 deletions lib/g3-types/src/net/tcp/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,14 @@ pub struct TcpListenConfig {

impl Default for TcpListenConfig {
fn default() -> Self {
TcpListenConfig::new(SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0))
}
}

impl TcpListenConfig {
pub fn new(address: SocketAddr) -> Self {
TcpListenConfig {
address: SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
address,
ipv6only: false,
#[cfg(target_os = "linux")]
transparent: false,
Expand All @@ -49,9 +55,7 @@ impl Default for TcpListenConfig {
scale: 0,
}
}
}

impl TcpListenConfig {
pub fn check(&self) -> anyhow::Result<()> {
if self.address.port() == 0 {
return Err(anyhow!("no listen port is set"));
Expand Down

0 comments on commit c79d126

Please sign in to comment.