@@ -2,7 +2,7 @@ use pyo3::prelude::*;
2
2
3
3
use log:: debug;
4
4
use socket2:: { Domain , Protocol , Socket , Type } ;
5
- use std:: net:: SocketAddr ;
5
+ use std:: net:: { IpAddr , SocketAddr } ;
6
6
7
7
#[ pyclass]
8
8
#[ derive( Debug ) ]
@@ -13,26 +13,19 @@ pub struct SocketHeld {
13
13
#[ pymethods]
14
14
impl SocketHeld {
15
15
#[ 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) ;
20
24
debug ! ( "{}" , address) ;
25
+ // reuse port is not available on windows
26
+ #[ cfg( not( target_os = "windows" ) ) ]
21
27
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
- }
28
28
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
36
29
socket. set_reuse_address ( true ) ?;
37
30
socket. bind ( & address. into ( ) ) ?;
38
31
socket. listen ( 1024 ) ?;
0 commit comments