1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//! Cross-platform library to retrieve network sockets information.
//! Tries to be optimal by using low-level OS APIs instead of command line utilities.
//! Provides unified interface and returns data structures which may have additional fields depending on platform.
//!
//! # Example
//!
//! ```rust
//! use netstat2::*;
//!
//! # fn main() -> Result<(), netstat2::error::Error> {
//! let af_flags = AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6;
//! let proto_flags = ProtocolFlags::TCP | ProtocolFlags::UDP;
//! let sockets_info = get_sockets_info(af_flags, proto_flags)?;
//!
//! for si in sockets_info {
//!     match si.protocol_socket_info {
//!         ProtocolSocketInfo::Tcp(tcp_si) => println!(
//!             "TCP {}:{} -> {}:{} {:?} - {}",
//!             tcp_si.local_addr,
//!             tcp_si.local_port,
//!             tcp_si.remote_addr,
//!             tcp_si.remote_port,
//!             si.associated_pids,
//!             tcp_si.state
//!         ),
//!         ProtocolSocketInfo::Udp(udp_si) => println!(
//!             "UDP {}:{} -> *:* {:?}",
//!             udp_si.local_addr, udp_si.local_port, si.associated_pids
//!         ),
//!     }
//! }
//! #     Ok(())
//! # }
//! ```
#![allow(non_camel_case_types)]
#![allow(unused_imports)]

#[macro_use]
extern crate bitflags;

mod integrations;
mod types;

pub use crate::integrations::*;
pub use crate::types::*;

// Cannot use `cfg(test)` here since `rustdoc` won't look at it.
#[cfg(debug_assertions)]
mod test_readme {
    macro_rules! calculated_doc {
        ($doc:expr, $id:ident) => {
            #[doc = $doc]
            enum $id {}
        }
    }

    calculated_doc!(include_str!("../README.md"), _DoctestReadme);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{IpAddr, Ipv4Addr, TcpListener, UdpSocket};
    use std::process;

    #[test]
    fn listening_tcp_socket_is_found() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();

        let open_port = listener.local_addr().unwrap().port();
        let pid = process::id();

        let af_flags = AddressFamilyFlags::all();
        let proto_flags = ProtocolFlags::TCP;

        let sock_info = get_sockets_info(af_flags, proto_flags).unwrap();

        assert!(!sock_info.is_empty());

        let sock = sock_info
            .into_iter()
            .find(|s| s.associated_pids.contains(&pid))
            .unwrap();

        assert_eq!(
            sock.protocol_socket_info,
            ProtocolSocketInfo::Tcp(TcpSocketInfo {
                local_addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
                local_port: open_port,
                remote_addr: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
                remote_port: 0,
                state: TcpState::Listen,
            })
        );
        assert_eq!(sock.associated_pids, vec![pid]);
    }

    #[test]
    fn listening_udp_socket_is_found() {
        let listener = UdpSocket::bind("127.0.0.1:0").unwrap();

        let open_port = listener.local_addr().unwrap().port();
        let pid = process::id();

        let af_flags = AddressFamilyFlags::all();
        let proto_flags = ProtocolFlags::UDP;

        let sock_info = get_sockets_info(af_flags, proto_flags).unwrap();

        assert!(!sock_info.is_empty());

        let sock = sock_info
            .into_iter()
            .find(|s| s.associated_pids.contains(&pid))
            .unwrap();

        assert_eq!(
            sock.protocol_socket_info,
            ProtocolSocketInfo::Udp(UdpSocketInfo {
                local_addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
                local_port: open_port,
            })
        );
        assert_eq!(sock.associated_pids, vec![pid]);
    }

    #[test]
    fn result_is_ok_for_any_flags() {
        let af_flags_combs = (0..AddressFamilyFlags::all().bits() + 1)
            .filter_map(AddressFamilyFlags::from_bits)
            .collect::<Vec<AddressFamilyFlags>>();
        let proto_flags_combs = (0..ProtocolFlags::all().bits() + 1)
            .filter_map(ProtocolFlags::from_bits)
            .collect::<Vec<ProtocolFlags>>();
        for af_flags in af_flags_combs.iter() {
            for proto_flags in proto_flags_combs.iter() {
                assert!(get_sockets_info(*af_flags, *proto_flags).is_ok());
            }
        }
    }

    #[test]
    fn result_is_empty_for_empty_flags() {
        let sockets_info =
            get_sockets_info(AddressFamilyFlags::empty(), ProtocolFlags::empty()).unwrap();
        assert!(sockets_info.is_empty());
    }
}