3 个版本 (重大更改)

0.2.0 2024 年 4 月 7 日
0.1.0 2024 年 4 月 6 日
0.0.1 2024 年 4 月 6 日

#7 in #process-information


2 crate 中使用

MIT 许可证

300KB
8K SLoC

netsock Crates.io License

跨平台网络套接字信息库。

功能

  • 检索 TCP 和 UDP 套接字信息
  • 支持 IPv4 和 IPv6
  • 获取带有进程信息的套接字信息

支持的平台

  • Linux
  • macOS
  • Windows

用法

netsock 添加到您的依赖项

[dependencies]
netsock = "0.2"

有关更多详细信息,请参阅 示例文档

示例

use netsock::family::AddressFamilyFlags;
use netsock::protocol::ProtocolFlags; 
use netsock::socket::ProtocolSocketInfo;
use netsock::get_sockets;

fn main() {
    // Combine IPv4 and IPv6 address family flags to search for sockets across both families.
    let af_flags = AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6;

    // Combine TCP and UDP protocol flags to search for both types of sockets.
    let proto_flags = ProtocolFlags::TCP | ProtocolFlags::UDP;

    // Call get_sockets with the specified address family and protocol flags.
    // This function returns a Result, which we match on to handle both the Ok and Err cases.
    match get_sockets(af_flags, proto_flags) {
        Ok(sockets) => {
            // If successful, iterate over the returned sockets and print their information.
            for socket in sockets {
                // Print the socket and process information
                match socket.protocol_socket_info {
                    ProtocolSocketInfo::Tcp(tcp_socket) => println!(
                        "[TCP] {}:{} -> {}:{} {:?} - [{}]",
                        tcp_socket.local_addr,
                        tcp_socket.local_port,
                        tcp_socket.remote_addr,
                        tcp_socket.remote_port,
                        socket.processes,
                        tcp_socket.state
                    ),
                    ProtocolSocketInfo::Udp(udp_socket) => println!(
                        "[UDP] {}:{} -> *:* {:?}",
                        udp_socket.local_addr, udp_socket.local_port, socket.processes
                    ),
                }
            }
        }
        Err(e) => {
            // If an error occurs, print the error message.
            eprintln!("Error: {}", e);
        }
    }
}

灵感来自

依赖项

~0.4–36MB
~547K SLoC