Repository navigation
API Reference
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.
- 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
Frontend (React) ββ Tauri IPC ββ Backend (Rust)
β β β
UI Components Command Invocation Core Logic
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);
}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);
}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);
}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);
}interface DHCPLog {
id: string;
timestamp: string;
sourceIp: string;
destinationIp: string;
sourceMac: string;
destinationMac: string;
messageType: DHCPMessageType;
options: DHCPOption[];
rawData: string;
interface: string;
}interface NetworkInterface {
name: string;
description: string;
isActive: boolean;
ipAddresses: string[];
macAddress: string;
type: InterfaceType;
}enum DHCPMessageType {
DISCOVER = 'DISCOVER',
OFFER = 'OFFER',
REQUEST = 'REQUEST',
ACK = 'ACK',
NAK = 'NAK',
RELEASE = 'RELEASE',
INFORM = 'INFORM'
}interface DHCPOption {
code: number;
length: number;
value: string;
description: string;
}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 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
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 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
#[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": "Error message description",
"code": "ERROR_CODE",
"details": "Additional error details"
}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);
}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);
}interface AppSettings {
general: GeneralSettings;
network: NetworkSettings;
monitoring: MonitoringSettings;
alerts: AlertSettings;
performance: PerformanceSettings;
}interface GeneralSettings {
theme: 'light' | 'dark' | 'auto';
language: string;
autoUpdate: boolean;
updateFrequency: 'daily' | 'weekly' | 'monthly' | 'never';
}interface NetworkSettings {
defaultInterface: string;
bufferSize: number;
timeout: number;
promiscuousMode: boolean;
customFilters: string[];
}interface MonitoringSettings {
option50Detection: boolean;
alertThreshold: number;
logLevel: 'debug' | 'info' | 'warning' | 'error';
deepInspection: boolean;
}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();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);
}interface CaptureStatistics {
totalPackets: number;
packetsPerSecond: number;
errors: number;
startTime: string;
duration: number;
interfaceName: string;
bufferUsage: number;
memoryUsage: number;
}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);
}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);
}interface AlertConfig {
option50Alerts: boolean;
highTrafficAlerts: boolean;
errorAlerts: boolean;
performanceAlerts: boolean;
notificationMethods: NotificationMethod[];
thresholds: AlertThresholds;
}interface Alert {
id: string;
timestamp: string;
type: AlertType;
severity: 'low' | 'medium' | 'high' | 'critical';
message: string;
details: Record<string, any>;
acknowledged: boolean;
}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);
}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);
}type ExportFormat = 'csv' | 'json' | 'xml' | 'txt';interface LogFilters {
startTime?: string;
endTime?: string;
sourceIp?: string;
destinationIp?: string;
messageType?: DHCPMessageType;
interface?: string;
}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);
}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);
}interface PermissionStatus {
networkAccess: boolean;
fileSystem: boolean;
administrator: boolean;
notifications: boolean;
autoStart: boolean;
}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);
}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);
}interface TestResult {
success: boolean;
packetsCaptured: number;
errors: number;
duration: number;
performance: PerformanceMetrics;
}interface ValidationResult {
valid: boolean;
errors: string[];
warnings: string[];
recommendations: string[];
}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 [];
}
}
}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
}
}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);
}
}
}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);
}
}
}After learning the API:
- Explore Usage Guide for practical examples
- Check Configuration for API settings
- Review Troubleshooting for API issues
- Return to Wiki Home for more information
- Documentation: Check this API reference
- Examples: Review usage examples
- GitHub Issues: Report API bugs
- Community: Ask questions in discussions
- 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