@@ -2,7 +2,7 @@ use pyo3::prelude::*;
22
33use log:: debug;
44use socket2:: { Domain , Protocol , Socket , Type } ;
5- use std:: net:: SocketAddr ;
5+ use std:: net:: { IpAddr , SocketAddr } ;
66
77#[ pyclass]
88#[ derive( Debug ) ]
@@ -13,26 +13,19 @@ pub struct SocketHeld {
1313#[ pymethods]
1414impl SocketHeld {
1515 #[ new]
16- #[ cfg( not( target_os = "windows" ) ) ]
17- pub fn new ( address : String , port : i32 ) -> PyResult < SocketHeld > {
18- let socket = Socket :: new ( Domain :: IPV4 , Type :: STREAM , Some ( Protocol :: TCP ) ) ?;
19- let address: SocketAddr = format ! ( "{}:{}" , address, port) . parse ( ) ?;
16+ pub fn new ( ip : String , port : u16 ) -> PyResult < SocketHeld > {
17+ let ip: IpAddr = ip. parse ( ) ?;
18+ let socket = if ip. is_ipv4 ( ) {
19+ Socket :: new ( Domain :: IPV4 , Type :: STREAM , Some ( Protocol :: TCP ) ) ?
20+ } else {
21+ Socket :: new ( Domain :: IPV6 , Type :: STREAM , Some ( Protocol :: TCP ) ) ?
22+ } ;
23+ let address = SocketAddr :: new ( ip, port) ;
2024 debug ! ( "{}" , address) ;
25+ // reuse port is not available on windows
26+ #[ cfg( not( target_os = "windows" ) ) ]
2127 socket. set_reuse_port ( true ) ?;
22- socket. set_reuse_address ( true ) ?;
23- socket. bind ( & address. into ( ) ) ?;
24- socket. listen ( 1024 ) ?;
25-
26- Ok ( SocketHeld { socket } )
27- }
2828
29- #[ new]
30- #[ cfg( target_os = "windows" ) ]
31- pub fn new ( address : String , port : i32 ) -> PyResult < SocketHeld > {
32- let socket = Socket :: new ( Domain :: IPV4 , Type :: STREAM , Some ( Protocol :: TCP ) ) ?;
33- let address: SocketAddr = format ! ( "{}:{}" , address, port) . parse ( ) ?;
34- debug ! ( "{}" , address) ;
35- // reuse port is not available on windows
3629 socket. set_reuse_address ( true ) ?;
3730 socket. bind ( & address. into ( ) ) ?;
3831 socket. listen ( 1024 ) ?;
0 commit comments