1- use netstat2:: { AddressFamilyFlags , get_sockets_info, ProtocolFlags , ProtocolSocketInfo } ;
21use crate :: { to_error, CommonError } ;
32
3+ #[ cfg( target_os = "macos" ) ]
4+ use crate :: darwin:: netstat;
5+ #[ cfg( target_os = "linux" ) ]
6+ use crate :: linux:: netstat;
7+ #[ cfg( target_os = "windows" ) ]
8+ use crate :: win:: netstat;
9+
410#[ cfg_attr( debug_assertions, derive( Debug ) ) ]
511#[ derive( Clone ) ]
612pub struct NetInterface {
@@ -22,39 +28,44 @@ pub struct NetStat {
2228 pub remote_addr : String ,
2329 pub protocol : String ,
2430 pub pid : String ,
25- // pub uid: u32,
2631 pub sk_state : String ,
2732}
2833
2934pub fn get_netstat ( ) -> Result < Vec < NetStat > , CommonError > {
3035 let mut netstats = Vec :: new ( ) ;
31-
32- let af_flags = AddressFamilyFlags :: IPV4 | AddressFamilyFlags :: IPV6 ;
33- let proto_flags = ProtocolFlags :: TCP | ProtocolFlags :: UDP ;
34- let sockets_info = to_error ! ( get_sockets_info( af_flags, proto_flags) ) ?;
35-
36- for si in sockets_info {
37- let pid: Vec < String > = si. associated_pids . iter ( ) . map ( |n| n. to_string ( ) ) . collect ( ) ;
38- match si. protocol_socket_info {
39- ProtocolSocketInfo :: Tcp ( tcp_si) => {
40- netstats. push ( NetStat {
41- local_addr : tcp_si. local_addr . to_string ( ) ,
42- remote_addr : tcp_si. remote_addr . to_string ( ) ,
43- protocol : "tcp" . to_string ( ) ,
44- pid : pid. join ( "," ) ,
45- sk_state : tcp_si. state . to_string ( )
46- } )
47- } ,
48- ProtocolSocketInfo :: Udp ( udp_si) => {
49- netstats. push ( NetStat {
50- local_addr : udp_si. local_addr . to_string ( ) ,
51- remote_addr : "" . to_string ( ) ,
52- protocol : "udp" . to_string ( ) ,
53- pid : pid. join ( "," ) ,
54- sk_state : "" . to_string ( )
55- } )
56- }
57- }
36+
37+ let sockets = to_error ! ( netstat:: get_sockets( true , true , true , true ) ) ?;
38+
39+ for socket in sockets {
40+ netstats. push ( NetStat {
41+ local_addr : socket. local_addr ,
42+ remote_addr : socket. remote_addr ,
43+ protocol : socket. protocol ,
44+ pid : socket. pid . to_string ( ) ,
45+ sk_state : socket. state ,
46+ } ) ;
5847 }
48+
5949 Ok ( netstats)
60- }
50+ }
51+
52+ #[ cfg( test) ]
53+ mod tests {
54+ use super :: * ;
55+
56+ #[ test]
57+ fn test_get_netstat ( ) {
58+ let result = get_netstat ( ) ;
59+ assert ! ( result. is_ok( ) , "Should get netstat information" ) ;
60+ let netstats = result. unwrap ( ) ;
61+ assert ! ( !netstats. is_empty( ) , "Should have some network connections" ) ;
62+
63+ for netstat in netstats {
64+ assert ! (
65+ !netstat. local_addr. is_empty( ) ,
66+ "Local address should not be empty"
67+ ) ;
68+ assert ! ( !netstat. protocol. is_empty( ) , "Protocol should not be empty" ) ;
69+ }
70+ }
71+ }
0 commit comments