From 825cafabdce7dcab67f0de81cbb32205b621101d Mon Sep 17 00:00:00 2001 From: wuyaoping Date: Thu, 20 Oct 2022 16:21:46 +0800 Subject: [PATCH 1/2] `SocketHeld::new` refactor --- src/shared_socket.rs | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/src/shared_socket.rs b/src/shared_socket.rs index e40af77db..993d8b888 100644 --- a/src/shared_socket.rs +++ b/src/shared_socket.rs @@ -13,26 +13,14 @@ pub struct SocketHeld { #[pymethods] impl SocketHeld { #[new] - #[cfg(not(target_os = "windows"))] pub fn new(address: String, port: i32) -> PyResult { let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?; let address: SocketAddr = format!("{}:{}", address, port).parse()?; debug!("{}", address); + // reuse port is not available on windows + #[cfg(not(target_os = "windows"))] socket.set_reuse_port(true)?; - socket.set_reuse_address(true)?; - socket.bind(&address.into())?; - socket.listen(1024)?; - - Ok(SocketHeld { socket }) - } - #[new] - #[cfg(target_os = "windows")] - pub fn new(address: String, port: i32) -> PyResult { - let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?; - let address: SocketAddr = format!("{}:{}", address, port).parse()?; - debug!("{}", address); - // reuse port is not available on windows socket.set_reuse_address(true)?; socket.bind(&address.into())?; socket.listen(1024)?; From 3cd94b0b34deb172b61e114ae454d098f0ddc4c1 Mon Sep 17 00:00:00 2001 From: wuyaoping Date: Fri, 21 Oct 2022 21:21:03 +0800 Subject: [PATCH 2/2] Support both ipv4 and ipv6 --- src/shared_socket.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/shared_socket.rs b/src/shared_socket.rs index 993d8b888..e11196eec 100644 --- a/src/shared_socket.rs +++ b/src/shared_socket.rs @@ -2,7 +2,7 @@ use pyo3::prelude::*; use log::debug; use socket2::{Domain, Protocol, Socket, Type}; -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; #[pyclass] #[derive(Debug)] @@ -13,9 +13,14 @@ pub struct SocketHeld { #[pymethods] impl SocketHeld { #[new] - pub fn new(address: String, port: i32) -> PyResult { - let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?; - let address: SocketAddr = format!("{}:{}", address, port).parse()?; + pub fn new(ip: String, port: u16) -> PyResult { + let ip: IpAddr = ip.parse()?; + let socket = if ip.is_ipv4() { + Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))? + } else { + Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP))? + }; + let address = SocketAddr::new(ip, port); debug!("{}", address); // reuse port is not available on windows #[cfg(not(target_os = "windows"))]