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

SocketHeld::new refactor #294

Merged
merged 2 commits into from
Oct 29, 2022
Merged
Changes from all commits
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
29 changes: 11 additions & 18 deletions src/shared_socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -13,26 +13,19 @@ pub struct SocketHeld {
#[pymethods]
impl SocketHeld {
#[new]
#[cfg(not(target_os = "windows"))]
pub fn new(address: String, port: i32) -> PyResult<SocketHeld> {
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<SocketHeld> {
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"))]
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<SocketHeld> {
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)?;
Expand Down