Skip to content

API Reference

Iyotee edited this page Aug 24, 2025 · 1 revision

API Reference

πŸ”Œ Overview

DHCP Monitor provides a comprehensive API for integrating with external systems, automating monitoring tasks, and building custom applications. The API is built on Tauri's IPC (Inter-Process Communication) system, providing secure and efficient communication between the frontend and backend.

πŸ—οΈ Architecture

API Structure

  • Frontend API: React/TypeScript interface for UI components
  • Backend API: Rust functions exposed through Tauri commands
  • IPC Layer: Secure communication between frontend and backend
  • Error Handling: Comprehensive error handling and validation

Communication Flow

Frontend (React) ←→ Tauri IPC ←→ Backend (Rust)
     ↓                    ↓              ↓
  UI Components    Command Invocation  Core Logic

πŸ“‘ Frontend API

Core Functions

startCapture(interfaceName: string): Promise<void>

Start DHCP packet capture on the specified network interface.

Parameters:

  • interfaceName: Name of the network interface to monitor

Returns: Promise that resolves when capture starts

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  await invoke('start_capture', { interfaceName: 'Ethernet' });
  console.log('Capture started successfully');
} catch (error) {
  console.error('Failed to start capture:', error);
}

stopCapture(): Promise<void>

Stop the currently running DHCP packet capture.

Returns: Promise that resolves when capture stops

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  await invoke('stop_capture');
  console.log('Capture stopped successfully');
} catch (error) {
  console.error('Failed to stop capture:', error);
}

getLogs(): Promise<DHCPLog[]>

Retrieve all captured DHCP logs.

Returns: Promise that resolves to array of DHCP logs

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const logs = await invoke('get_logs');
  console.log('Retrieved logs:', logs);
} catch (error) {
  console.error('Failed to get logs:', error);
}

getNetworkInterfaces(): Promise<NetworkInterface[]>

Get list of available network interfaces.

Returns: Promise that resolves to array of network interfaces

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const interfaces = await invoke('get_network_interfaces');
  console.log('Available interfaces:', interfaces);
} catch (error) {
  console.error('Failed to get interfaces:', error);
}

Data Types

DHCPLog

interface DHCPLog {
  id: string;
  timestamp: string;
  sourceIp: string;
  destinationIp: string;
  sourceMac: string;
  destinationMac: string;
  messageType: DHCPMessageType;
  options: DHCPOption[];
  rawData: string;
  interface: string;
}

NetworkInterface

interface NetworkInterface {
  name: string;
  description: string;
  isActive: boolean;
  ipAddresses: string[];
  macAddress: string;
  type: InterfaceType;
}

DHCPMessageType

enum DHCPMessageType {
  DISCOVER = 'DISCOVER',
  OFFER = 'OFFER',
  REQUEST = 'REQUEST',
  ACK = 'ACK',
  NAK = 'NAK',
  RELEASE = 'RELEASE',
  INFORM = 'INFORM'
}

DHCPOption

interface DHCPOption {
  code: number;
  length: number;
  value: string;
  description: string;
}

πŸ¦€ Backend API

Tauri Commands

start_capture

Start DHCP packet capture on specified interface.

Rust Function:

#[tauri::command]
pub async fn start_capture(
    interface_name: String,
    state: tauri::State<'_, AppState>
) -> Result<(), String> {
    // Implementation
}

Parameters:

  • interface_name: String - Name of network interface

Returns: Result indicating success or error

stop_capture

Stop currently running DHCP packet capture.

Rust Function:

#[tauri::command]
pub async fn stop_capture(
    state: tauri::State<'_, AppState>
) -> Result<(), String> {
    // Implementation
}

Returns: Result indicating success or error

get_logs

Retrieve all captured DHCP logs.

Rust Function:

#[tauri::command]
pub async fn get_logs(
    state: tauri::State<'_, AppState>
) -> Result<Vec<DHCPLog>, String> {
    // Implementation
}

Returns: Result containing vector of DHCP logs or error

get_network_interfaces

Get list of available network interfaces.

Rust Function:

#[tauri::command]
pub async fn get_network_interfaces() -> Result<Vec<NetworkInterface>, String> {
    // Implementation
}

Returns: Result containing vector of network interfaces or error

Error Handling

DHCPError

#[derive(Debug, thiserror::Error)]
pub enum DHCPError {
    #[error("Interface not found: {0}")]
    InterfaceNotFound(String),
    
    #[error("Capture already running")]
    CaptureAlreadyRunning,
    
    #[error("Capture not running")]
    CaptureNotRunning,
    
    #[error("Permission denied: {0}")]
    PermissionDenied(String),
    
    #[error("Network error: {0}")]
    NetworkError(String),
    
    #[error("Invalid configuration: {0}")]
    InvalidConfiguration(String),
}

Error Response Format

{
  "error": "Error message description",
  "code": "ERROR_CODE",
  "details": "Additional error details"
}

πŸ”§ Configuration API

Settings Management

getSettings(): Promise<AppSettings>

Retrieve current application settings.

Returns: Promise that resolves to application settings

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const settings = await invoke('get_settings');
  console.log('Current settings:', settings);
} catch (error) {
  console.error('Failed to get settings:', error);
}

updateSettings(settings: Partial<AppSettings>): Promise<void>

Update application settings.

Parameters:

  • settings: Partial settings object with values to update

Returns: Promise that resolves when settings are updated

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  await invoke('update_settings', {
    settings: {
      theme: 'dark',
      autoStart: true,
      logRetention: 30
    }
  });
  console.log('Settings updated successfully');
} catch (error) {
  console.error('Failed to update settings:', error);
}

Settings Types

AppSettings

interface AppSettings {
  general: GeneralSettings;
  network: NetworkSettings;
  monitoring: MonitoringSettings;
  alerts: AlertSettings;
  performance: PerformanceSettings;
}

GeneralSettings

interface GeneralSettings {
  theme: 'light' | 'dark' | 'auto';
  language: string;
  autoUpdate: boolean;
  updateFrequency: 'daily' | 'weekly' | 'monthly' | 'never';
}

NetworkSettings

interface NetworkSettings {
  defaultInterface: string;
  bufferSize: number;
  timeout: number;
  promiscuousMode: boolean;
  customFilters: string[];
}

MonitoringSettings

interface MonitoringSettings {
  option50Detection: boolean;
  alertThreshold: number;
  logLevel: 'debug' | 'info' | 'warning' | 'error';
  deepInspection: boolean;
}

πŸ“Š Monitoring API

Real-time Monitoring

subscribeToLogs(callback: (log: DHCPLog) => void): () => void

Subscribe to real-time log updates.

Parameters:

  • callback: Function called when new logs arrive

Returns: Unsubscribe function

Example:

import { invoke } from '@tauri-apps/api/core';

const unsubscribe = await invoke('subscribe_to_logs', {
  callback: (log: DHCPLog) => {
    console.log('New log received:', log);
    // Process new log
  }
});

// Later, unsubscribe
unsubscribe();

getStatistics(): Promise<CaptureStatistics>

Get current capture statistics.

Returns: Promise that resolves to capture statistics

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const stats = await invoke('get_statistics');
  console.log('Capture statistics:', stats);
} catch (error) {
  console.error('Failed to get statistics:', error);
}

Statistics Types

CaptureStatistics

interface CaptureStatistics {
  totalPackets: number;
  packetsPerSecond: number;
  errors: number;
  startTime: string;
  duration: number;
  interfaceName: string;
  bufferUsage: number;
  memoryUsage: number;
}

🚨 Alert API

Alert Management

configureAlerts(config: AlertConfig): Promise<void>

Configure alert settings.

Parameters:

  • config: Alert configuration object

Returns: Promise that resolves when alerts are configured

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  await invoke('configure_alerts', {
    config: {
      option50Alerts: true,
      highTrafficAlerts: true,
      errorAlerts: true,
      notificationMethods: ['desktop', 'sound']
    }
  });
  console.log('Alerts configured successfully');
} catch (error) {
  console.error('Failed to configure alerts:', error);
}

getAlertHistory(): Promise<Alert[]>

Get history of triggered alerts.

Returns: Promise that resolves to array of alerts

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const alerts = await invoke('get_alert_history');
  console.log('Alert history:', alerts);
} catch (error) {
  console.error('Failed to get alert history:', error);
}

Alert Types

AlertConfig

interface AlertConfig {
  option50Alerts: boolean;
  highTrafficAlerts: boolean;
  errorAlerts: boolean;
  performanceAlerts: boolean;
  notificationMethods: NotificationMethod[];
  thresholds: AlertThresholds;
}

Alert

interface Alert {
  id: string;
  timestamp: string;
  type: AlertType;
  severity: 'low' | 'medium' | 'high' | 'critical';
  message: string;
  details: Record<string, any>;
  acknowledged: boolean;
}

πŸ“ Data Export API

Export Functions

exportLogs(format: ExportFormat, filters?: LogFilters): Promise<string>

Export logs in specified format.

Parameters:

  • format: Export format (CSV, JSON, XML)
  • filters: Optional filters to apply

Returns: Promise that resolves to exported data

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const csvData = await invoke('export_logs', {
    format: 'csv',
    filters: {
      startTime: '2024-01-01T00:00:00Z',
      endTime: '2024-01-31T23:59:59Z',
      messageType: 'REQUEST'
    }
  });
  console.log('Exported CSV data:', csvData);
} catch (error) {
  console.error('Failed to export logs:', error);
}

exportConfiguration(): Promise<string>

Export current application configuration.

Returns: Promise that resolves to configuration data

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const configData = await invoke('export_configuration');
  console.log('Exported configuration:', configData);
} catch (error) {
  console.error('Failed to export configuration:', error);
}

Export Types

ExportFormat

type ExportFormat = 'csv' | 'json' | 'xml' | 'txt';

LogFilters

interface LogFilters {
  startTime?: string;
  endTime?: string;
  sourceIp?: string;
  destinationIp?: string;
  messageType?: DHCPMessageType;
  interface?: string;
}

πŸ” Security API

Authentication and Permissions

checkPermissions(): Promise<PermissionStatus>

Check current application permissions.

Returns: Promise that resolves to permission status

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const permissions = await invoke('check_permissions');
  console.log('Permission status:', permissions);
} catch (error) {
  console.error('Failed to check permissions:', error);
}

requestPermissions(permissions: string[]): Promise<boolean>

Request additional permissions.

Parameters:

  • permissions: Array of permission names to request

Returns: Promise that resolves to success status

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const granted = await invoke('request_permissions', {
    permissions: ['network_access', 'file_system']
  });
  console.log('Permissions granted:', granted);
} catch (error) {
  console.error('Failed to request permissions:', error);
}

Permission Types

PermissionStatus

interface PermissionStatus {
  networkAccess: boolean;
  fileSystem: boolean;
  administrator: boolean;
  notifications: boolean;
  autoStart: boolean;
}

πŸ§ͺ Testing API

Development and Testing

testCapture(duration: number): Promise<TestResult>

Run a test capture for specified duration.

Parameters:

  • duration: Test duration in seconds

Returns: Promise that resolves to test results

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const result = await invoke('test_capture', { duration: 30 });
  console.log('Test capture result:', result);
} catch (error) {
  console.error('Failed to run test capture:', error);
}

validateConfiguration(): Promise<ValidationResult>

Validate current application configuration.

Returns: Promise that resolves to validation results

Example:

import { invoke } from '@tauri-apps/api/core';

try {
  const validation = await invoke('validate_configuration');
  console.log('Configuration validation:', validation);
} catch (error) {
  console.error('Failed to validate configuration:', error);
}

Test Types

TestResult

interface TestResult {
  success: boolean;
  packetsCaptured: number;
  errors: number;
  duration: number;
  performance: PerformanceMetrics;
}

ValidationResult

interface ValidationResult {
  valid: boolean;
  errors: string[];
  warnings: string[];
  recommendations: string[];
}

πŸ“š Usage Examples

Basic Monitoring Application

import { invoke } from '@tauri-apps/api/core';

class DHCPMonitor {
  private isRunning = false;

  async startMonitoring(interfaceName: string) {
    try {
      await invoke('start_capture', { interfaceName });
      this.isRunning = true;
      console.log('Monitoring started');
    } catch (error) {
      console.error('Failed to start monitoring:', error);
    }
  }

  async stopMonitoring() {
    try {
      await invoke('stop_capture');
      this.isRunning = false;
      console.log('Monitoring stopped');
    } catch (error) {
      console.error('Failed to stop monitoring:', error);
    }
  }

  async getCurrentLogs() {
    try {
      const logs = await invoke('get_logs');
      return logs;
    } catch (error) {
      console.error('Failed to get logs:', error);
      return [];
    }
  }
}

Real-time Dashboard

import { invoke } from '@tauri-apps/api/core';

class Dashboard {
  private updateInterval: NodeJS.Timeout;

  startRealTimeUpdates() {
    this.updateInterval = setInterval(async () => {
      try {
        const [logs, stats] = await Promise.all([
          invoke('get_logs'),
          invoke('get_statistics')
        ]);
        
        this.updateUI(logs, stats);
      } catch (error) {
        console.error('Failed to update dashboard:', error);
      }
    }, 1000);
  }

  stopRealTimeUpdates() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
  }

  private updateUI(logs: DHCPLog[], stats: CaptureStatistics) {
    // Update dashboard UI with new data
  }
}

πŸ”— Integration Examples

Webhook Integration

import { invoke } from '@tauri-apps/api/core';

class WebhookManager {
  async sendAlert(alert: Alert) {
    try {
      const webhookUrl = await invoke('get_setting', { key: 'webhookUrl' });
      
      if (webhookUrl) {
        await fetch(webhookUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(alert)
        });
      }
    } catch (error) {
      console.error('Failed to send webhook:', error);
    }
  }
}

Database Integration

import { invoke } from '@tauri-apps/api/core';

class DatabaseManager {
  async exportToDatabase() {
    try {
      const logs = await invoke('get_logs');
      const config = await invoke('export_configuration');
      
      // Send to database
      await this.saveToDatabase(logs, config);
    } catch (error) {
      console.error('Failed to export to database:', error);
    }
  }
}

πŸ“– Next Steps

After learning the API:

  1. Explore Usage Guide for practical examples
  2. Check Configuration for API settings
  3. Review Troubleshooting for API issues
  4. Return to Wiki Home for more information

πŸ†˜ API Support

Getting Help

  • Documentation: Check this API reference
  • Examples: Review usage examples
  • GitHub Issues: Report API bugs
  • Community: Ask questions in discussions

Best Practices

  • Error Handling: Always handle errors gracefully
  • Async/Await: Use modern async patterns
  • Type Safety: Leverage TypeScript for type safety
  • Performance: Consider performance implications
  • Security: Follow security best practices

Clone this wiki locally