Python API Reference

Programmatic access to NetScan's functionality for integration into your Python applications and scripts.

Overview

NetScan provides several Python modules that can be imported directly:

# MAC Address lookup
from helpers.mac_lookup import lookup_mac, lookup_vendor

# Network scanning
from helpers.scanner import NetworkScanner

# OUI database
from helpers.oui_parser import OUIDatabase

# Network utilities
from helpers.network_utils import get_local_ip, get_network_interfaces

# High-performance operations (if Rust module compiled)
from helpers.fast_core import normalize_mac, expand_cidr

MAC Lookup Module

Look up vendor information for MAC addresses.

lookup_mac(mac_address)

Look up vendor information for a single MAC address.

lookup_mac(mac_address: str) -> dict

Parameters

Name Type Description
mac_address str MAC address in any standard format

Returns

Dictionary containing vendor information:

{
    "mac": "00:50:56:C0:00:08",
    "vendor": "VMware, Inc.",
    "oui": "00:50:56",
    "is_private": False,
    "is_multicast": False
}

Example

from helpers.mac_lookup import lookup_mac

# Look up a MAC address
result = lookup_mac("00:50:56:C0:00:08")
print(f"Vendor: {result['vendor']}")  # VMware, Inc.

# Different formats work
result = lookup_mac("00-50-56-C0-00-08")
result = lookup_mac("005056C00008")

lookup_vendor(mac_address)

Get just the vendor name (faster than full lookup).

lookup_vendor(mac_address: str) -> str
from helpers.mac_lookup import lookup_vendor

vendor = lookup_vendor("AC:DE:48:00:11:22")
print(vendor)  # "Apple, Inc."

batch_lookup(mac_addresses)

Look up multiple MAC addresses efficiently.

batch_lookup(mac_addresses: List[str]) -> List[dict]
from helpers.mac_lookup import batch_lookup

macs = [
    "00:50:56:C0:00:08",
    "AC:DE:48:00:11:22",
    "B8:27:EB:12:34:56"
]

results = batch_lookup(macs)
for result in results:
    print(f"{result['mac']}: {result['vendor']}")

Network Scanner Module

Discover devices on the network.

NetworkScanner Class

class NetworkScanner(target: str = None, interface: str = None)

Parameters

Name Type Description
target str Target network in CIDR notation (auto-detected if not provided)
interface str Network interface to use (auto-detected if not provided)

Example

from helpers.scanner import NetworkScanner

# Create scanner (auto-detect network)
scanner = NetworkScanner()

# Or specify target
scanner = NetworkScanner(target="192.168.1.0/24")

# Quick scan
devices = scanner.quick_scan()
for device in devices:
    print(f"{device['ip']} - {device['mac']} - {device['vendor']}")

# Full scan with ports
devices = scanner.full_scan()
for device in devices:
    print(f"{device['ip']}: ports {device.get('ports', [])}")

Methods

quick_scan()

Fast network discovery using ARP and ping.

quick_scan() -> List[dict]
devices = scanner.quick_scan()
# Returns list of:
# {
#     "ip": "192.168.1.1",
#     "mac": "00:11:22:AA:BB:CC",
#     "vendor": "Netgear",
#     "hostname": "router.local",
#     "status": "online"
# }

full_scan(ports=None)

Deep scan including port detection.

full_scan(ports: List[int] = None) -> List[dict]
# Default common ports
devices = scanner.full_scan()

# Custom port list
devices = scanner.full_scan(ports=[22, 80, 443, 8080, 3389])

# Returns list with port information:
# {
#     "ip": "192.168.1.10",
#     "mac": "AC:DE:48:00:11:22",
#     "vendor": "Apple, Inc.",
#     "hostname": "macbook.local",
#     "ports": [22, 80],
#     "services": {"22": "ssh", "80": "http"}
# }

arp_scan()

ARP-only scan (fastest, requires privileges).

arp_scan() -> List[dict]

ping_scan()

ICMP ping sweep.

ping_scan() -> List[dict]

OUI Database Module

Direct access to the OUI (Organizationally Unique Identifier) database.

OUIDatabase Class

from helpers.oui_parser import OUIDatabase

# Load database
db = OUIDatabase()

# Look up OUI
vendor = db.lookup("00:50:56")
print(vendor)  # "VMware, Inc."

# Search vendors
results = db.search("Apple")
for oui, vendor in results:
    print(f"{oui}: {vendor}")

# Get all entries for vendor
apple_ouis = db.get_vendor_ouis("Apple")
print(f"Apple has {len(apple_ouis)} registered OUIs")

Methods

lookup(oui)

lookup(oui: str) -> str

search(query)

search(query: str) -> List[Tuple[str, str]]

update()

Download and update the OUI database.

update() -> bool
db = OUIDatabase()
if db.update():
    print("Database updated successfully")
else:
    print("Update failed")

Network Utilities

Helper functions for network operations.

from helpers.network_utils import (
    get_local_ip,
    get_network_interfaces,
    get_default_gateway,
    get_network_cidr,
    is_private_ip,
    validate_ip,
    validate_mac
)

# Get local IP address
ip = get_local_ip()
print(f"Local IP: {ip}")  # 192.168.1.10

# Get all network interfaces
interfaces = get_network_interfaces()
for iface in interfaces:
    print(f"{iface['name']}: {iface['ip']}")

# Get default gateway
gateway = get_default_gateway()
print(f"Gateway: {gateway}")  # 192.168.1.1

# Get network CIDR for current network
cidr = get_network_cidr()
print(f"Network: {cidr}")  # 192.168.1.0/24

# Validate addresses
print(is_private_ip("192.168.1.1"))  # True
print(is_private_ip("8.8.8.8"))       # False
print(validate_ip("192.168.1.1"))     # True
print(validate_mac("00:11:22:33:44:55"))  # True

Fast Core Module (Rust)

High-performance operations using the optional Rust backend.

💡 Note: The fast_core module automatically falls back to pure Python if the Rust module is not compiled. You can use it without worrying about availability.
from helpers.fast_core import (
    normalize_mac,
    normalize_mac_batch,
    expand_cidr,
    parse_oui_file,
    tcp_scan_async,
    RUST_AVAILABLE
)

# Check if Rust backend is available
print(f"Rust backend: {RUST_AVAILABLE}")

# Normalize MAC addresses (10-100x faster with Rust)
mac = normalize_mac("00:11:22:33:44:55")
print(mac)  # "00:11:22:33:44:55"

# Batch normalize (massively faster with Rust)
macs = ["001122334455", "AA-BB-CC-DD-EE-FF", "11:22:33:44:55:66"]
normalized = normalize_mac_batch(macs)

# Expand CIDR to IP list
ips = expand_cidr("192.168.1.0/24")
print(f"Generated {len(ips)} IPs")  # 254 IPs

# Parse OUI file (memory-mapped, very fast)
oui_dict = parse_oui_file("/path/to/oui.txt")

# Async TCP port scan
open_ports = tcp_scan_async("192.168.1.1", [22, 80, 443, 8080])
print(f"Open ports: {open_ports}")

Performance Comparison

Operation Python Rust Speedup
normalize_mac (1000x) 12ms 0.15ms ~80x
expand_cidr (/16) 850ms 45ms ~19x
parse_oui (30MB) 3.2s 180ms ~18x
tcp_scan (100 ports) 5.1s 0.3s ~17x

CLI Integration

Run NetScan commands from Python:

import subprocess
import json

def netscan_command(args):
    """Run netscan command and return JSON output."""
    result = subprocess.run(
        ["netscan"] + args + ["--json"],
        capture_output=True,
        text=True
    )
    return json.loads(result.stdout)

# MAC lookup
result = netscan_command(["-l", "00:50:56:C0:00:08"])
print(result["vendor"])

# Network scan
devices = netscan_command(["-s"])
for device in devices["devices"]:
    print(f"{device['ip']}: {device['vendor']}")

Complete Examples

Network Inventory Script

#!/usr/bin/env python3
"""Generate network inventory report."""

from helpers.scanner import NetworkScanner
from helpers.mac_lookup import lookup_mac
import json
from datetime import datetime

def generate_inventory(target=None):
    """Scan network and generate inventory."""
    scanner = NetworkScanner(target=target)
    devices = scanner.full_scan()
    
    inventory = {
        "timestamp": datetime.now().isoformat(),
        "target": target or scanner.target,
        "devices": []
    }
    
    for device in devices:
        # Enrich with vendor info
        mac_info = lookup_mac(device["mac"])
        device.update({
            "vendor_full": mac_info.get("vendor", "Unknown"),
            "is_private": mac_info.get("is_private", False)
        })
        inventory["devices"].append(device)
    
    inventory["summary"] = {
        "total_devices": len(devices),
        "vendors": list(set(d["vendor_full"] for d in devices))
    }
    
    return inventory

if __name__ == "__main__":
    inventory = generate_inventory()
    print(json.dumps(inventory, indent=2))
    
    # Save to file
    with open(f"inventory_{datetime.now():%Y%m%d}.json", "w") as f:
        json.dump(inventory, f, indent=2)

Device Monitor

#!/usr/bin/env python3
"""Monitor network for new devices."""

from helpers.scanner import NetworkScanner
import time

def monitor_network(interval=60):
    """Continuously monitor network for changes."""
    scanner = NetworkScanner()
    known_devices = set()
    
    print(f"Monitoring {scanner.target}...")
    print("Press Ctrl+C to stop\n")
    
    while True:
        try:
            devices = scanner.quick_scan()
            current_macs = {d["mac"] for d in devices}
            
            # Check for new devices
            new_macs = current_macs - known_devices
            for mac in new_macs:
                device = next(d for d in devices if d["mac"] == mac)
                print(f"[NEW] {device['ip']} - {device['mac']} ({device['vendor']})")
            
            # Check for devices that went offline
            offline_macs = known_devices - current_macs
            for mac in offline_macs:
                print(f"[OFFLINE] {mac}")
            
            known_devices = current_macs
            time.sleep(interval)
            
        except KeyboardInterrupt:
            print("\nMonitoring stopped.")
            break

if __name__ == "__main__":
    monitor_network()

Vendor Statistics

#!/usr/bin/env python3
"""Analyze vendor distribution on network."""

from helpers.scanner import NetworkScanner
from collections import Counter

def vendor_stats():
    """Get vendor statistics for network."""
    scanner = NetworkScanner()
    devices = scanner.quick_scan()
    
    vendors = Counter(d["vendor"] for d in devices)
    
    print(f"Network: {scanner.target}")
    print(f"Total devices: {len(devices)}\n")
    print("Vendor Distribution:")
    print("-" * 40)
    
    for vendor, count in vendors.most_common():
        pct = (count / len(devices)) * 100
        bar = "█" * int(pct / 5)
        print(f"{vendor[:25]:25} {count:3} ({pct:5.1f}%) {bar}")

if __name__ == "__main__":
    vendor_stats()