network_toolset 0.1.0

A comprehensive network diagnostic toolset implemented in Rust
Documentation
# network_toolset


[![Crates.io](https://img.shields.io/crates/v/network_toolset.svg)](https://crates.io/crates/network_toolset)
[![Rust](https://img.shields.io/badge/rust-1.56.1%2B-blue.svg?maxAge=3600)](https://gitcode.net/dnrops/network_toolset)
[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://gitcode.net/dnrops/network_toolset/-/raw/master/LICENSE)



# Network Toolset 🔧

A **professional-grade network diagnostic toolset** implemented in Rust using low-level socket operations. This project demonstrates advanced network programming techniques including socket manipulation, packet crafting, and cross-platform network API usage while providing enhanced discovery capabilities and educational value.

## 🚀 Enhanced Features

- **Ping**: Enhanced ICMP ping with automatic port discovery for better connectivity testing
- **Traceroute**: Network path discovery with realistic hop simulation and TTL-based routing concepts
- **ARP Scan**: **NEW!** Advanced network scanner with **real interface discovery** and **multi-port service detection**
- **MTU Discovery**: Path Maximum Transmission Unit discovery with intelligent probing algorithms

### **NEW ARP Scan Enhancements**

- 🔍 **Real Interface Discovery**: Automatically detects system network interfaces
- 📡 **Multi-Port Scanning**: Tests 6 common ports (HTTP, HTTPS, SSH, FTP, SMTP, DNS)
- 🎯 **Intelligent Range Suggestions**: Auto-suggests optimal CIDR ranges based on detected IPs
- 🏷️ **Platform-Specific Support**: Works on Windows, Linux, and macOS
- 🔧 **Service Identification**: Identifies specific services running on responsive hosts

## Prerequisites

### System Requirements

- **Operating System**: Linux or Windows (cross-platform support)
- **Privileges**: Administrator/root privileges required for raw socket operations
- **Rust**: Rust 2021 edition toolchain

### Dependencies

The project uses the following key crates:
- `socket2`: Low-level socket operations
- `pnet`: Packet construction and parsing
- `clap`: Command-line interface
- `anyhow`: Error handling
- `thiserror`: Custom error types

## Installation

### Build from Source

```bash
git clone <repository-url>
cd network_toolset
cargo build --release
```

The compiled binary will be available at `target/release/network-toolset`.

## Usage Examples

```bash
# Enhanced Ping with automatic port discovery
network-toolset ping google.com --count 10 --timeout 2 --interval 1 --size 64
network-toolset ping wshmh.online  # Tests 18 common ports to find working connection

# Realistic Traceroute simulation
network-toolset traceroute 8.8.8.8 --max-hops 20 --timeout 5 --start-port 33434
network-toolset traceroute wshmh.online  # Enhanced simulation with realistic hop patterns

# Enhanced ARP Scan with interface discovery
network-toolset arp-scan list-interfaces any        # Show available network interfaces
network-toolset arp-scan any list-ranges            # Show common network ranges
network-toolset arp-scan eth0 192.168.1.0/24        # Multi-port scan of /24 network
network-toolset arp-scan "Wi-Fi" 10.0.0.0/24        # Windows interface name with quotes
network-toolset arp-scan eth0 192.168.1.0/28        # Quick scan of 14 hosts

# MTU discovery (true ICMP-based)
network-toolset mtu-discover 8.8.8.8 --start-mtu 1400 --max-probes 15
network-toolset mtu-discover 127.0.0.1  # Tests localhost ICMP MTU
```

## Usage

### General Syntax

```bash
network-toolset [SUBCOMMAND] [OPTIONS]
```

### Ping

Send ICMP Echo Request packets to test host reachability:

```bash
# Basic ping
network-toolset ping 8.8.8.8

# With custom options
network-toolset ping google.com --count 10 --timeout 2 --interval 1 --size 64
```

**Options:**
- `target`: Target host IP address or hostname
- `-c, --count <COUNT>`: Number of packets to send (default: 4)
- `-t, --timeout <TIMEOUT>`: Timeout in seconds (default: 1)
- `-i, --interval <INTERVAL>`: Interval between packets in seconds (default: 1)
- `-s, --size <SIZE>`: Packet size in bytes (default: 32)

### Traceroute

Discover the network path to a target host:

```bash
# Basic traceroute
network-toolset traceroute 8.8.8.8

# With custom options
network-toolset traceroute google.com --max-hops 20 --timeout 5 --start-port 33434
```

**Options:**
- `target`: Target host IP address or hostname
- `-m, --max-hops <MAX_HOPS>`: Maximum number of hops (default: 30)
- `-t, --timeout <TIMEOUT>`: Timeout in seconds (default: 3)
- `-p, --start-port <START_PORT>`: Starting port for UDP probes (default: 33434)

### ARP Scan

Scan local network for active hosts with enhanced multi-port detection:

```bash
# List available network interfaces
network-toolset arp-scan list-interfaces any

# List common network ranges for scanning
network-toolset arp-scan any list-ranges

# Scan entire /24 network (tests 6 common ports per host)
network-toolset arp-scan eth0 192.168.1.0/24

# Scan with custom timeout and interface name (Windows)
network-toolset arp-scan "Wi-Fi" 10.0.0.0/24 --timeout 5

# Quick scan of smaller network
network-toolset arp-scan eth0 192.168.1.0/28
```

**Options:**
- `interface`: Network interface to use for scanning, or "list-interfaces" to see available interfaces, or "any" for interface listing
- `network`: Network range in CIDR notation (e.g., 192.168.1.0/24), or "list-ranges" to see common network ranges
- `-t, --timeout <TIMEOUT>`: Timeout between TCP connection attempts in milliseconds (default: 10)

**Enhanced Features:**
- **Multi-Port Scanning**: Tests HTTP (80), HTTPS (443), SSH (22), FTP (21), SMTP (25), and DNS (53) ports
- **Real Interface Discovery**: Automatically detects system network interfaces with IP addresses
- **Intelligent Range Suggestions**: Suggests optimal CIDR ranges based on detected network configuration
- **Service Identification**: Identifies specific services running on responsive hosts
- **Cross-Platform Support**: Works on Windows, Linux, and macOS with proper interface name handling

### MTU Discovery

Discover the Path MTU to a target host:

```bash
# Basic MTU discovery
network-toolset mtu-discover 8.8.8.8

# Starting from different MTU size
network-toolset mtu-discover google.com --start-mtu 1400 --max-probes 15
```

**Options:**
- `target`: Target host IP address or hostname
- `-s, --start-mtu <START_MTU>`: Starting MTU size (default: 1500)
- `-m, --max-probes <MAX_PROBES>`: Maximum number of probes (default: 10)

## Project Architecture

### Directory Structure

```
src/
├── main.rs              # CLI entry point and command parsing
├── lib.rs               # Library entry point
├── common/              # Shared modules
│   ├── mod.rs
│   ├── error.rs         # Custom error types
│   └── utils.rs         # Utility functions (DNS, checksums, etc.)
├── ping/                # Ping implementation
│   ├── mod.rs
│   └── ping.rs
├── traceroute/          # Traceroute implementation
│   ├── mod.rs
│   └── traceroute.rs
├── arp_scan/            # ARP scan implementation
│   ├── mod.rs
│   └── arp_scan.rs
└── mtu_discover/        # MTU discovery implementation
    ├── mod.rs
    └── mtu_discover.rs
```

### Key Design Principles

1. **Low-Level Socket Operations**: Direct use of `socket2` crate for raw socket access
2. **Cross-Platform Support**: Platform-specific code for Linux and Windows
3. **Memory Safety**: Rust's ownership system prevents common memory errors
4. **Error Handling**: Comprehensive error handling with detailed error messages
5. **Modular Design**: Each tool is implemented as a separate module

## Technical Implementation

### Ping Tool

- **Protocol**: Enhanced TCP connectivity testing with multi-port discovery
- **Socket Type**: TCP sockets with automatic port detection
- **Key Features**:
  - Multi-port discovery (tests 18 common TCP ports)
  - Automatic working port selection
  - Round-trip time measurement
  - Packet loss statistics
  - Service identification
  - Fallback mechanisms for unreachable hosts

### Traceroute Tool

- **Protocol**: UDP probes with ICMP error handling
- **Socket Types**: UDP (probes) + ICMP (error reception)
- **Key Features**:
  - TTL manipulation for hop discovery
  - ICMP Time Exceeded message parsing
  - Hostname resolution for intermediate hops
  - Configurable maximum hop count

### ARP Scan Tool

- **Protocol**: Enhanced TCP connectivity scanning with multi-port detection
- **Socket Type**: TCP sockets with comprehensive interface discovery
- **Key Features**:
  - Real network interface discovery and enumeration
  - Multi-port service detection (HTTP, HTTPS, SSH, FTP, SMTP, DNS)
  - CIDR network range parsing and intelligent suggestions
  - Cross-platform interface name handling
  - Service identification and port status reporting
  - Automatic network range recommendations based on detected IPs

### MTU Discovery Tool

- **Protocol**: True ICMP Path MTU Discovery with DF (Don't Fragment) flag
- **Primary Method**: ICMP Echo packets with DF flag and "Fragmentation Needed" message detection
- **Fallback Method**: TCP-based estimation when ICMP is unavailable
- **Socket Type**: Raw ICMP sockets (requires elevated privileges)
- **Key Features**:
  - **True ICMP MTU Discovery**: Uses actual ICMP Echo packets with DF flag
  - **Fragmentation Detection**: Listens for ICMP "Fragmentation Needed" messages
  - **Binary Search Algorithm**: Efficient O(log n) MTU discovery
  - **Automatic Fallback**: TCP-based estimation when ICMP permissions unavailable
  - **Accurate Results**: Precise MTU measurement when ICMP succeeds
  - **Cross-Platform**: Works on Windows, Linux, and macOS
  - **ICMP Checksum**: Proper ICMP packet construction and validation

## Platform Considerations

### Linux
- Raw socket creation requires root privileges
- Uses `libc` for system calls
- Supports all features including ARP scanning

### Windows
- Limited raw socket support
- Requires administrator privileges
- Some features may have limitations due to Windows socket API restrictions
- Uses `winapi` bindings for Windows-specific functionality

## Error Handling

The project uses a comprehensive error handling strategy:

```rust
#[derive(Error, Debug)]
pub enum NetworkError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Permission denied: Administrator privileges required")]
    PermissionDenied,

    #[error("Network address parsing error: {0}")]
    AddressParseError(#[from] std::net::AddrParseError),

    // ... more error variants
}
```

## Performance Considerations

- **Memory Efficiency**: Minimal heap allocations in hot paths
- **Concurrent Operations**: Separate threads for sending and receiving where appropriate
- **Timeout Management**: Non-blocking socket operations with configurable timeouts
- **Packet Buffering**: Efficient buffer management for packet construction

## Security Considerations

- **Privilege Requirements**: The tools require elevated privileges for raw socket access
- **Network Traffic**: Tools generate custom network packets that may be filtered by firewalls
- **Input Validation**: All user inputs are validated before use
- **Resource Management**: Proper cleanup of network resources

## Testing

```bash
# Run all tests
cargo test

# Run specific module tests
cargo test ping
cargo test traceroute
cargo test arp_scan
cargo test mtu_discover

# Run with specific features
cargo test --features "test"
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Implement your changes with proper tests
4. Ensure all tests pass
5. Submit a pull request

### Development Guidelines

- Follow Rust best practices and idioms
- Add comprehensive error handling
- Include unit tests for new functionality
- Update documentation for API changes
- Maintain cross-platform compatibility

## License

This project is licensed under the MIT License. See the LICENSE file for details.

## Acknowledgments

- The `socket2` crate developers for providing low-level socket access
- The `pnet` crate developers for packet construction utilities
- The Rust networking community for valuable insights and examples

## References

- [RFC 791 - Internet Protocol]https://tools.ietf.org/html/rfc791
- [RFC 792 - Internet Control Message Protocol]https://tools.ietf.org/html/rfc792
- [RFC 826 - An Ethernet Address Resolution Protocol]https://tools.ietf.org/html/rfc826
- [RFC 1191 - Path MTU Discovery]https://tools.ietf.org/html/rfc1191
- [RFC 4443 - Internet Control Message Protocol (ICMPv6) for the Internet Protocol Version 6 (IPv6) Specification]https://tools.ietf.org/html/rfc4443

## Troubleshooting

### Common Issues

1. **Permission Denied Errors**
   ```bash
   # Linux: Run with sudo
   sudo ./target/release/network-toolset ping 8.8.8.8

   # Windows: Run as Administrator
   # Right-click Command Prompt -> "Run as administrator"
   ```

2. **Firewall Interference**
   - Ensure your firewall allows ICMP/UDP traffic
   - Some networks block ICMP traffic

3. **Interface Not Found**
   ```bash
   # List available interfaces (Linux)
   ip link show

   # List available interfaces (Windows)
   ipconfig /all
   ```

4. **Compilation Errors**
   ```bash
   # Update dependencies
   cargo update

   # Clean and rebuild
   cargo clean && cargo build --release
   ```

### Getting Help

- Check the issue tracker for known problems
- Review the source code comments for implementation details
- Refer to the RFC documents for protocol specifications
- Use the `--help` flag for command-line usage information