Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(tcp): reducing branching in Transport::create_socket #4328

Merged
merged 6 commits into from
Aug 18, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 39 additions & 9 deletions transports/tcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,13 +346,12 @@ where
}
}

fn create_socket(&self, socket_addr: &SocketAddr) -> io::Result<Socket> {
let domain = if socket_addr.is_ipv4() {
Domain::IPV4
} else {
Domain::IPV6
};
let socket = Socket::new(domain, Type::STREAM, Some(socket2::Protocol::TCP))?;
fn create_socket(&self, socket_addr: SocketAddr) -> io::Result<Socket> {
let socket = Socket::new(
Domain::for_address(socket_addr),
Type::STREAM,
Some(socket2::Protocol::TCP),
)?;
if socket_addr.is_ipv6() {
socket.set_only_v6(true)?;
}
Expand All @@ -375,7 +374,7 @@ where
id: ListenerId,
socket_addr: SocketAddr,
) -> io::Result<ListenStream<T>> {
let socket = self.create_socket(&socket_addr)?;
let socket = self.create_socket(socket_addr)?;
socket.bind(&socket_addr.into())?;
socket.listen(self.config.backlog as _)?;
socket.set_nonblocking(true)?;
Expand Down Expand Up @@ -476,7 +475,7 @@ where
log::debug!("dialing {}", socket_addr);

let socket = self
.create_socket(&socket_addr)
.create_socket(socket_addr)
.map_err(TransportError::Other)?;

if let Some(addr) = self.port_reuse.local_dial_addr(&socket_addr.ip()) {
Expand Down Expand Up @@ -1329,4 +1328,35 @@ mod tests {
assert!(rt.block_on(cycle_listeners::<tokio::Tcp>()));
}
}

#[test]
fn test_listens_ipv4_ipv6_separately() {
fn test<T: Provider>(port: u16) {
let mut tcp = Transport::<T>::default().boxed();
let listener_id = ListenerId::next();
tcp.listen_on(
listener_id,
format!("/ip4/0.0.0.0/tcp/{port}").parse().unwrap(),
)
.unwrap();
tcp.listen_on(
ListenerId::next(),
format!("/ip6/::/tcp/{port}").parse().unwrap(),
)
.unwrap();
}
#[cfg(feature = "async-io")]
{
async_std::task::block_on(async {
test::<async_io::Tcp>(3001);
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
})
}
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap();
rt.block_on(async {
test::<async_io::Tcp>(4001);
});
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
}
}